Reputation: 3204
I have a large array in Swift. I want to initialize all members to the same value (i.e. it could be zero or some other value). What would be the best approach?
Upvotes: 107
Views: 79066
Reputation: 81
For swift 3 and above, if you want to initialize with Array key word:
var threeDoubles = Array<Double>(repeating: 0.0, count: 3)
We can add the type of value we want to work with this array. For more information you can read the document provide by apple.
Upvotes: 0
Reputation: 2416
Actually, it's quite simple with Swift. As mentioned in the Apple's doc, you can initialize an array with the same repeated value like this:
With old Swift version:
var threeDoubles = [Double](count: 3, repeatedValue: 0.0)
Since Swift 3.0:
var threeDoubles = [Double](repeating: 0.0, count: 3)
which would give:
[0.0, 0.0, 0.0]
Upvotes: 206
Reputation: 9064
This would be an answer in Swift 3:
var threeDoubles = [Double]( repeating: 0.0, count: 3 )
Upvotes: 37