Swift Arrays

In Swift, an array is a special type of variable that contains multiple values of the same type. The following string variable, ‘fname’, has been defined and initialised with the name ‘Bob’.

var fname = "Bob"

If multiple names need to be stored, instead of having a different variable for each, an array could be used.

var fnames = [ "Bob", "George", "Fred", "Alan" ]

If an empty array needs to be defined, then the type must be included.

var fnames:[String] = []

Values can then be added to the array using the 'append' method.

fnames.append("Bob")
fnames.append("George")
fnames.append("Fred")
fnames.append("Alan")

If it is necessary to access an individual element of an array, this can be achieved by using its index value. Index values start at zero for the first item in the array.

print(fnames[2])

Here, the third item in the array, with an index value of two, is displayed.

In order to display all of the elements in an array, a ‘for’ loop can be used.

for name in fnames
{
    print(name)
}

The resulting output will list all the elements of the array on a separate line.

Bob
George
Fred
Alan

As well as being able to add elements to the end of an array, using the 'append' method, it is also possible to insert a value, at a specified index location using the 'insert' method.

fnames.insert("Fiona", at: 2)

Here the name 'Fiona' is added at index position two, the third item in the array. All elements, from this position onwards, are moved one place.

Bob
George
Fiona
Fred
Alan

It is also possible to use the index value to change an existing element.

fnames[1] = "James"

In the above example, the name 'George', at index position one, is changed to 'James'.

The final use for the index position, combined with the 'remove' method, is the ability to delete an element from an array.

fnames.remove(at: 1)

Here, the element updated in the previous example is removed, using its index value of one. Similarly to inserting an element, all subsequent values are moved back one index position.

As well as being able to remove an item at a specific index position, it is also possible to remove the last item in the array with the 'removeLast' method.

fnames.removeLast()

Further Reading