Swift init Array with capacity

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.


Swift 3 / Swift 4 / Swift 5

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

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

Tags:

Arrays

Swift