[ACCEPTED]-Swift: Creating an Array with a Default Value of distinct object instances-instantiation

Accepted answer
Score: 38

Classes are reference types, therefore – as 12 you noticed – all array elements in

var users = [User](count: howManyUsers, repeatedValue:User(thinkTime: 10.0))

reference 11 the same object instance (which is created 10 first and then passed as an argument to 9 the array initializer).

For a struct type you would 8 get a different result.

A possible solution:

var users = (0 ..< howManyUsers).map { _ in User(thinkTime: 10.0) }

Here, a 7 User instance is created for each of the array 6 indices.

If you need that frequently then 5 you could define an array init method which 4 takes an "autoclosure" parameter:

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) )

Now the 3 second argument User(thinkTime: 10.0) is wrapped by the compiler 2 into a closure, and the closure is executed 1 for each array index.


Update for Swift 3:

extension Array {
    public init(count: Int, elementCreator: @autoclosure () -> Element) {
        self = (0 ..< count).map { _ in elementCreator() }
    }
}
Score: 0

Swift 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)

0

More Related questions