105

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?

P i
  • 29,020
  • 36
  • 159
  • 267
m_power
  • 3,156
  • 5
  • 33
  • 54

2 Answers2

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
  • 17
    It 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
  • @wcochran Did you discover a better way to do this? – WestCoastProjects May 14 '20 at 16:48
  • @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 )
ppaulojr
  • 3,579
  • 4
  • 29
  • 56
Andi
  • 8,154
  • 3
  • 30
  • 34
  • 1
    Autosuggest states [Double](repeatElement(3.22, count: 5)), still explicitly typing (repeating, count) seems to be valid – Ashwin G Nov 17 '16 at 03:10