You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.@inlinablepublicinit(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.
To create array containing number of repeated value in Swift, we can use Array.init(repeating:count:)
However, if we read Collection Types guide about Creating an Array with a Default Value
And if we take a closer look at its signature
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.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 initiationThe text was updated successfully, but these errors were encountered: