LEARN SWIFT

Buy the PDF

Chapter 6 Arrays

An array is a list of values. In Swift, arrays are typed. You declare the type of the array (or Swift infers it) and you can only add items that are of the same type to the array. You can’t generally store multiple different types in an array. There are ways to include objects of different types in an array which we’ll touch on later, but for the most part you’ll stick to only having one type of thing in your array.

1 var arrayOfInts:[Int] = [1, 2]
2 var arrayOfInts2 = [1, 2]

We declare an array in Swift by using a list of values surrounded by square brackets. Line 1 shows how to explicitly declare an array of integers. Line 2 accomplishes the same thing as we initialize the array with value [1, 2] and Swift infers from that that it’s an array of integers.

var arrayOfInts:[Int] = [1, 2]
arrayOfInts.isEmpty // false

We can use isEmpty to check if an array is empty.

1 var arrayOfInts = [1, 2]
2 arrayOfInts.append(3)
3 arrayOfInts += [4,5]
4 arrayOfInts  // [1, 2, 3, 4, 5]
5 
6 arrayOfInts.append("A string") // Error

We can add an element to the end of the array using append. Here we append the value 3 to the array at line 2.

We can also use the addition assignment operator, +=, to add one or more elements into the array. Line 3 shows how to add add multiple values to the array at once.

Line 6 shows that the array is typed. It was initialized as an array of integers, so we can only add integers to it. Here we get an error if we try to add a string to the Integer array.

We can access the elements of the array using an index or a range. Arrays in Swift are zero indexed i.e. use index 0 to access the first element in the array. Lines 2 and 3 below show how we can get the element at index 0 and 2 respectively. We can also use a range to get a sub-array from an array. Line 4 shows how we get a sub-array back with the elements from index 2 to 4.

1 var arrayOfInts  = [1, 2]
2 arrayOfInts[0] // 1
3 arrayOfInts[2] // 3
4 arrayOfInts[2...4] // [3, 4, 5]
5 
6 arrayOfInts.insert(6, atIndex: 5)
7 arrayOfInts.insert(0, atIndex: 0)

We insert elements into the array using insert method, with key atIndex. E.g. At lines 6 and 7 we insert value 6 at index 5, and value 0 at index 0.

We can remove elements from the array using removeAtIndex or removeLast. removeAtIndex removes the element at a specified index. Here we remove the last element from the array - i.e. the element at index 6 - by specifying the index that we want to remove (line 2). We can also remove the last element of the array with removeLast (line 4).

1 var arrayOfInts  = [1, 2]
2 arrayOfInts.removeAtIndex(6)
3 arrayOfInts // [0, 1, 2, 3, 4, 5]
4 arrayOfInts.removeLast()
5 arrayOfInts // [0, 1, 2, 3, 4]

To iterate over an array we use a for-in loop. The example below loops through the array and prints out the square of each value in the array. This yields the element of the array into the variable i at each iteration of the loop. If we look at the console output we can see the square of each value in the array being printed.

var arrayOfInts = [1, 2]
for i in arrayOfInts{
    print(i * i)
}

If we want to iterate over an array with both the index and the value at each iteration, we can use the enumerate method of the array. This will yield both the index and the value for each element of the array. If we look at the console here we see the index and the square of each value of each element of the array being printed.

var arrayOfInts = [1, 2]
for (index, value) in arrayOfInts.enumerate() {
    print("\(index) -> \(value * value)")
}

You can create an empty array using the syntax shown at line 2 below.

1 var arrayOfInts = [1, 2]
2 var emptyInts = [Int]()
3 emptyInts.append(3)
4 
5 var cells = [Bool](count: 64, repeatedValue: false)
6 cells.count // 64
7 cells[10]   // false
8 
9 var allInts = arrayOfInts + emptyInts

We declare the type of the array in square brackets, followed by empty round brackets. This will create an empty array of integers (the round brackets here may seem unusual but the reason they’re there is that we’re calling a function. We see at line 4 how we can pass arguments to that function to get different initialization behaviour). Once we’ve created the empty array we can add values to it as usual.

You can also create an array of a predefined size filled with a default value. Line 5 shows how to create a fixed size array of booleans and initialize them all to false. We do this by passing the count and repeatedValue keys to the function to create the array.

You can also create a new array by merging two existing arrays of the same type using the + operator. At line 9 we create a new array of integers by merging both of our existing arrays.

let firstFiveInts = [1, 2, 3, 4, 5]
firstFiveInts.append(6) // Error

All our examples so far have used var to declare arrays. Thus they are all mutable. You can declare an immutable array by using the let keyword. For an immutable array, any method that would modify the array will generate an error. For example, the above example creates an immutable array of integers. If we try to append a new value to that array we get an error.