o.uinn
o.uinn

Reputation: 848

How can I make an immutable Array in swift that has different instances of the same class

So in swift there isn't a distinct difference between an Array, and a mutable Array, but the Apple docs say it is always better to use an immutable Array when you know the number of elements. So say I want to make an immutable Array of type Hi that has x different elements of type Hi.

I can do this but it will assign the same instance to each element in the array

var array = [Hi](count: x, repeatedValue: Hi())

I can do this but the elements in the array are let, and therefore not editable

var array = [Hi](count: x, repeatedValue: nil)
for hi in array {
hi = Hi()
}

Is there a constructor for Array that takes a closure so I can tell it how to make each element?

Upvotes: 0

Views: 171

Answers (1)

GoZoner
GoZoner

Reputation: 70155

As an expression, simply:

[Int](count: x, repeatedValue: 0).map { _ in Hi() }

or, more succinctly, as suggested by @vacawama and using Range.map

(1...x).map { _ in Hi() }

Upvotes: 2

Related Questions