Swift: Creating an Array with a Default Value of distinct object instances Swift: Creating an Array with a Default Value of distinct object instances arrays arrays

Swift: Creating an Array with a Default Value of distinct object instances


Classes are reference types, therefore – as you noticed – all arrayelements in

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

reference the same object instance (which is created first and thenpassed as an argument to the array initializer).

For a struct type you would get a different result.

A possible solution:

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

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

If you need that frequently then you could define an array initmethod which 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 second argument User(thinkTime: 10.0) is wrapped by the compiler into a closure, and the closure is executed for eacharray index.


Update for Swift 3:

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


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)