Swift - Creating an Empty Array

Introduction

In Swift, you can create an empty array of a specific data type using the initializer syntax, as follows:

var names = [String]()

The preceding creates an empty array of type String.

To populate the array, you can use the append() method:

Demo

var names = [String]()
names.append("S")
names.append("W")
names.append("H")
names.append("F")
names.append("H")

for name in names {
   print(name)  //print out all the names in the array
}

Result

To make names an empty array again, assign it to a pair of empty brackets:

names =  []

The following example creates an empty array of type Int :

var nums =  [Int]()

You can create an array of a specific size and initialize each element in the array to a specific value:

var scores = [Float](count:5, repeatedValue:0.0)

The count parameter indicates the size of the array and the repeatedValue parameter specifies the initial value for each element in the array.

The preceding statement can also be rewritten without explicitly specifying the type:

var scores = Array (count:5, repeatedValue:0.0)

The type can be inferred from the argument passed to the repeatedValue parameter.

If you print out the values for each element in the array as shown here

Demo

var scores = Array (count:5, repeatedValue:0.0)
for score in scores {
    print(score)/*from  w ww.j a v a  2  s .  c om*/
}

Related Topic