Start learning free

LESSON 97 OF 349 · ARRAYS I

Exceeding Array Bounds in Swift in Swift

Lesson

When accessing Array data with indices, the most common problem we can run into is exceeding the Array's bounds.

Remember, the items of an Array are indexed from 0 to count - 1. Any index which is not in this range is invalid.

When you try to access an item with an invalid index, Swift throws an error:

var ourArray = [50, 40, 30]

// Valid indices: 0, 1, 2
print(ourArray[0]) // Output: 50
print(ourArray[2]) // Output: 30

// Invalid indices: 3, 30, -1
print(ourArray[3]) // Fatal error: Index out of range
print(ourArray[30]) // Fatal error: Index out of range
print(ourArray[-1]) // Fatal error: Index out of range

As programmers, we always want to make sure that we don't exceed one Array's bounds in our programs.


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 1
    Ctrl + Enter to check

    Exceeding Array Bounds in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free