3

Surprisingly, the code below prints SAME while the initializer should call the Z() constructor each time. How can I initialize the array using this method with distinct instances of Z?

import Foundation

class Z {
    var i: Int = 0
}

var z: [Z] = [Z](repeating: Z(), count: 10)

if z[0] === z[1] {
    print("SAME")
} else {
    print("NOT SAME")
}
0

1 Answer 1

6

I made an extension just for this!

extension Array {    
    /// Create a new Array whose values are generated by the given closure.
    /// - Parameters:
    ///     - count:            The number of elements to generate
    ///     - elementGenerator: The closure that generates the elements.
    ///                         The index into which the element will be
    ///                         inserted is passed into the closure.
    public init(generating elementGenerator: (Int) -> Element, count: Int) {
        self = (0..<count).map(elementGenerator)
    }
}

class Z {
    var i: Int = 0
}

let z = Array(generating: { _ in Z() }, count: 10)

print(z)
Sign up to request clarification or add additional context in comments.

6 Comments

self.indices returns zero.
Can you show me your test case?
I just fixed the typo (called it generating) with init(generating elementGenerator): (Int) -> Element, count: Int) and tried it with let z = [Z](generating: { _ in Z() }, count: 10). Array is empty.
No luck. self.indices inside your init returns an empty range. I tested with Swift 3.1.
Oh yeah, i was playing around with it and forgot to refer that part. It's fixed now.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.