Issue #793
To create array containing number of repeated value in Swift, we can use Array.init(repeating:count:)
let fiveZs = Array(repeating: "Z", count: 5)
print(fiveZs)
// Prints "["Z", "Z", "Z", "Z", "Z"]"
However, if we read Collection Types guide about Creating an Array with a Default Value
Swift’s Array type also provides an initializer for creating an array of a certain size with all of its values set to the same default value. You pass this initializer a default value of the appropriate type (called repeating): and the number of times that value is repeated in the new array (called count):
And if we take a closer look at its signature
- repeatedValue: The element to repeat.
- count: The number of times to repeat the value passed in the
`repeating` parameter. `count` must be zero or greater.
@inlinable public init(repeating repeatedValue: Element, count: Int)
Class in Swift are reference type, this Array.repeating
method creates one instance of the class, and repeat that same instance n times. In the code below, we get an array of 5 elements, each is pointing to one same instance.
class Robot {}
let robots = Array(repeating: Robot(), count: 5)
That behavior is not what you want. In case you want to create different instances, you can map
on a range and @autoclosure
to do lazy initiation
extension Array {
public init(count: Int, createElement: @autoclosure () -> Element) {
self = (0 ..< count).map { _ in createElement() }
}
}
let robots = Array(count: 5, createElement: Robot())