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
The capacity property returns the total number of elements present in the array without allocating any additional storage.
To create an array of specific size in Swift, use Array initialiser syntax and pass this specific size. We also need to pass the default value for these elements in the Array. The following code snippet returns an Array of size 4 with default value of 0 .
To create an empty string array in Swift, specify the element type String for the array and assign an empty array to the String array variable.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With