2 回答
TA贡献1842条经验 获得超21个赞
类是引用类型,因此-正如您所注意到的-中的所有数组元素
var users = [User](count: howManyUsers, repeatedValue:User(thinkTime: 10.0))
引用相同的对象实例(首先创建该实例,然后将其作为参数传递给数组初始化器)。
对于struct类型,您将得到不同的结果。
可能的解决方案:
var users = (0 ..< howManyUsers).map { _ in User(thinkTime: 10.0) }
在这里,User为每个数组索引创建一个实例。
如果您经常需要,则可以定义一个带有“ autoclosure”参数的数组初始化方法:
extension Array {
public init(count: Int, @autoclosure elementCreator: () -> Element) {
self = (0 ..< count).map { _ in elementCreator() }
}
}
var users = Array(count: howManyUsers, elementCreator: User(thinkTime: 10.0) )
现在,第二个参数User(thinkTime: 10.0)由编译器包装到一个闭包中,并对每个数组索引执行闭包。
Swift 3更新:
extension Array {
public init(count: Int, elementCreator: @autoclosure () -> Element) {
self = (0 ..< count).map { _ in elementCreator() }
}
}
TA贡献1770条经验 获得超3个赞
迅捷5
extension MSRoom {
static var dummyDefaultRoom: MSRoom = {
let members = MSRoom.Member.dummyMembers(maxCount: 6)
let ownerUser = members.first!.user
var room = MSRoom(id: "98236482724", info: .init(name: "Ahmed's Room", description: "your default room", isPrivate: true), owner: ownerUser)
room.dateCreated = Date(timeIntervalSince1970: 1565222400)
room.currentMembers = members
return room
}()
}
let rooms = [MSRoom](repeating: MSRoom.dummyDefaultRoom, count: 10)
- 2 回答
- 0 关注
- 817 浏览
添加回答
举报