Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to repeat array of object in Swift #793

Open
onmyway133 opened this issue Mar 22, 2021 · 0 comments
Open

How to repeat array of object in Swift #793

onmyway133 opened this issue Mar 22, 2021 · 0 comments
Labels

Comments

@onmyway133
Copy link
Owner

onmyway133 commented Mar 22, 2021

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())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant