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

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

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

reference the same object instance (which is created first and then passed 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 init method 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 each array index.


Update for Swift 3:

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