Start learning free

LESSON 96 OF 415 · ARRAYS I

Accessing Array Elements in Swift

Lesson Read the full explanation

We can access the data inside an Array using indexes.

Arrays also use zero-based indexing, so the first element in an Array has an index of 0.

var array = [50, 60, 70]

print(array[0]) // Output: 50

let data = array[1]
print(data) // Output: 60

Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    SWIFT · ARRAYS I

    Accessing Elements in Swift, explained

    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.

    1. The second fruit. Index 1 holds the second item, so print(fruits[1]) prints kiwi. Index 2 would give the third item.
    2. 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 prints 96.
    3. Last minus first. The last of four elements has index 3, so print(ages[3] - ages[0]) prints 7.
    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. Use ages[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 Int can serve as an index.
    • An invalid index stops the program with a fatal error.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free