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

m_power picture m_power · Jun 2, 2014 · Viewed 64.8k times · Source

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?

Answer

moumoute6919 picture moumoute6919 · Jun 12, 2014

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]