How to initialize all array elements with the same value in Swift?

I have a large array in Swift. I want to initialize all members with the same value (that is, it can be zero or some other value). What would be a better approach?

+74
arrays initialization swift
Jun 02 '14 at 19:36
source share
2 answers

Actually, it is quite simple with Swift. As mentioned in the Apple doc , you can initialize an array with the same duplicate value as this:

With the old version of Swift :

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] 
+139
Jun 12 '14 at 2:37
source share

This will be the answer in Swift 3:

 var threeDoubles = [Double]( repeating: 0.0, count: 3 ) 
+32
Sep 30 '16 at 15:54
source share



All Articles