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")
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With