JuJoDi JuJoDi - 2 months ago 20
Swift Question

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

Answer

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.