Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift init Array with capacity

Tags:

arrays

swift

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  
like image 407
JuJoDi Avatar asked Jun 09 '14 16:06

JuJoDi


People also ask

What is array capacity in Swift?

The capacity property returns the total number of elements present in the array without allocating any additional storage.

How do I set the size of an array in Swift?

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 .

How do you create an empty array in Swift?

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.


1 Answers

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.

like image 152
Ben Clayton Avatar answered Sep 18 '22 18:09

Ben Clayton