Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an array using `repeating:count:` with distinct objects? [duplicate]

Tags:

swift

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")
}
like image 954
John Difool Avatar asked Dec 28 '25 08:12

John Difool


1 Answers

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)
like image 169
Alexander Avatar answered Dec 30 '25 23:12

Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!