Swift - Creating an Empty Array


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:


var names = [String]()

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


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


var scores = Array (count:5, repeatedValue:0.0)
for score in scores {
    print(score)/*from  www.  ja v  a2 s.com*/

Related Topic