JuJoDi
JuJoDi

Reputation: 14955

Swift init Array with capacity

How do I initialize an Array in swift with a specific capacity?

I've tried:

var grid = Array <Square> ()
grid.reserveCapacity(16)

but get the error

expected declaration 

Upvotes: 45

Views: 41806

Answers (5)

ScottyBlades
ScottyBlades

Reputation: 13973

WARNING:

If you use the Array(repeating:count:) initializer, you will encounter odd and unexpected behavior when using common array methods such as append( which will immediately defeat the purpose of reserving capacity by adding the new value outside the created capacity instead of an earlier point in the array.

BETTER PRACTICE:

Swift arrays dynamically double to meet the storage needs of your array so you don't necessarily need to reserve capacity in most cases. However, there is a speed cost when you don't specify the size ahead of time as the system needs to find a new memory location with enough space and copy over each item one by one in O(N) speed every time it doubles. On average, reallocation tends towards big O(LogN) as the array size doubles.

If you reserve capacity you can bring the reallocation process down from O(N) or O(NlogN) on average down to nothing if you can accurately anticipate the size of the array ahead of time. Here is the documentation.

You can do so by calling reserveCapacity(:) on arrays.

var myArray: [Double] = []
myArray.reserveCapacity(10000)

Because array capacity expands as needed and fast, this really isn't necessary in a vast majority of cases.

For 99.9% of use cases attempting to manually control this will not provide any noticeable performance improvements if any at all, and isn't worth the trade off of confusing other developers that will have to wonder why you were so concerned with this.

Upvotes: 5

Mert Celik
Mert Celik

Reputation: 715

Swift 3 / Swift 4 / Swift 5

var grid : [Square] = []
grid.reserveCapacity(16)

I believe it can be achieved in one line as well.

Upvotes: 37

Ben Clayton
Ben Clayton

Reputation: 82209

How about:

class Square {

}

var grid = Array<Square>(count: 16, repeatedValue: Square());

Though this will call the constructor for each square.

If you made the array have optional Square instances you could use:

var grid2 = Array<Square?>(count: 16, repeatedValue: nil);

EDIT: With Swift3 this initializer signature has changed to the following:

var grid3 = Array<Square>(repeating: Square(), count: 16)

or

var grid4 = [Square](repeating: Square(), count: 16)

Of course, both also work with Square? and nil.

Upvotes: 54

Yan
Yan

Reputation: 1727

var actions:[AnyObject?] = [AnyObject?](count: 3, repeatedValue: nil)

Upvotes: 13

Andrew Ebling
Andrew Ebling

Reputation: 10283

Try:

var grid = Array<Square>(count: 16, repeatedValue: aSquare)

Upvotes: 4

Related Questions