How to initialize all members of an array to the same value in Swift?

ArraysInitializationSwift

Arrays Problem Overview


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?

Arrays Solutions


Solution 1 - Arrays

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]

Solution 2 - Arrays

This would be an answer in Swift 3:

var threeDoubles = [Double]( repeating: 0.0, count: 3 )

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionm_powerView Question on Stackoverflow
Solution 1 - Arraysmoumoute6919View Answer on Stackoverflow
Solution 2 - ArraysarauterView Answer on Stackoverflow