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?
Asked
Active
Viewed 7.5k times
105
-
2Create the array, loop through all of the elements and set each one, just like you would in any other programming language. – Robert Harvey Jun 02 '14 at 19:38
-
20`var a = Array(count:100, repeatedValue:0)` is exactly the answer to this valid question. – Rod Jun 05 '14 at 05:37
-
@Rod, I'll try that. If the question is reopened you can post it as an answer. – m_power Jun 05 '14 at 14:10
-
2Looping is at least an order of magnitude slower than using vector math. – μολὼν.λαβέ Apr 30 '15 at 20:20
2 Answers
204
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]

Julien Kode
- 5,010
- 21
- 36

moumoute6919
- 2,406
- 1
- 14
- 17
-
17It seems that in Swift3 it changed to `var threeDoubles = [Double]( repeating: 0.0, count: 3 )` – ppaulojr Oct 10 '16 at 19:42
-
I have discovered this is really sloooooooow, a 16MB array takes seconds to clear this way. In C , `memset(p, 0, 16*1024*1024)` is practically instantaneous. – wcochran Oct 04 '17 at 19:03
-
-
@javadba Nope. Still surprised there is no efficient mechanism to do this in Swift when the hardware can do this fast. Maybe its worth investigating the source. – wcochran May 14 '20 at 16:53
37
This would be an answer in Swift 3:
var threeDoubles = [Double]( repeating: 0.0, count: 3 )
-
1Autosuggest states [Double](repeatElement(3.22, count: 5)), still explicitly typing (repeating, count) seems to be valid – Ashwin G Nov 17 '16 at 03:10