JuJoDi JuJoDi - 1 year ago 179
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> ()

but get the error

expected declaration

Answer Source

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)


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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download