Reading an element by index
The data inside an array is reached through indexes. Swift arrays are zero-based, so the first element has index 0. Put the index in square brackets after the array's name:
var array = [50, 60, 70]
print(array[0]) // 50
let data = array[1]
print(data) // 60
The expression array[1] produces a value, so you can print it directly or keep it in a constant, as above. Because the array holds Int values, data is an Int too.
Indexes inside expressions
An index can be any expression that produces an Int: a literal, a variable or a calculation.
let i = 2
print(array[i]) // 70
print(array[i - 1]) // 60
This is how loops walk through arrays: a counter variable changes, and array[counter] reads each element in turn.
The last element
With four elements the indexes are 0 to 3. In general the last index is count - 1, where count is the number of elements:
let ages = [14, 32, 50, 21]
print(ages[ages.count - 1]) // 21
The array also has a last property, but it gives an optional value (Optional(21) when printed), since an empty array has no last element. Indexing gives the plain Int.
Reading every element
A loop with a counter reads each position in turn. The range 0..<ages.count runs from 0 up to, but not including, the count, so it produces exactly the valid indexes:
let ages = [14, 32, 50, 21]
var total = 0
for i in 0..<ages.count {
total += ages[i]
}
print(total) // 117
When you don't need the position itself, for age in ages hands you each element directly, with no index to get wrong. Reach for an index when the position matters, for example to compare neighbours or to read only part of the array.
Checking an index first
Reading an invalid index crashes the program, so when an index comes from somewhere you can't predict, check it before you use it:
let wanted = 4
if wanted >= 0 && wanted < ages.count {
print(ages[wanted])
} else {
print("out of range") // this branch runs
}
The exercise, step by step
The starter code declares fruits and ages as constants. Add three print statements below them.
- The second fruit. Index 1 holds the second item, so
print(fruits[1])printskiwi. Index 2 would give the third item. - The sum of the first three ages. Read the elements at indexes 0, 1 and 2 and add them inside the call:
print(ages[0] + ages[1] + ages[2]). Swift evaluates the sum first and prints96. - Last minus first. The last of four elements has index 3, so
print(ages[3] - ages[0])prints7.
let fruits = ["mango", "kiwi", "grapefruit"]
let ages = [14, 32, 50, 21]
print(fruits[1])
print(ages[0] + ages[1] + ages[2])
print(ages[3] - ages[0])
The output is kiwi, 96 and 7, one per line.
Common mistakes
- Off-by-one indexes. The second item is at index 1. Asking for "the first three" means indexes 0 to 2, not 1 to 3.
- Indexing past the end.
ages[4]on a four-element array crashes the program when it runs. - Using a negative index. Swift does not count from the end, so
ages[-1]crashes too. Useages[ages.count - 1]. - Using parentheses.
ages(1)is a different syntax, a function call, and doesn't compile for an array. Elements use square brackets.
Key takeaways
- The first element of an array is at index 0, and the last is at
count - 1. array[index]gives the element, with the array's element type.- Any expression that produces an
Intcan serve as an index. - An invalid index stops the program with a fatal error.
