When accessing string characters with indices, the most common problem we can run into is exceeding the string's bounds.
Remember, the characters of a string are normally indexed from 0 to count - 1.
Any index which is strictly greater than count - 1 is invalid.
When you try to access a character with an invalid index, Swift crashes the program with an index out of range error:
var car = "ford"
// Valid indices: 0, 1, 2, 3
print(Array(car)[0]) // Output: f
print(Array(car)[3]) // Output: d
// Invalid indices: 4, 30
print(Array(car)[4]) // Crashes: index out of range
print(Array(car)[30]) // Crashes: index out of range
This code would crash at the first invalid index, Array(car)[4], because there is no character there.
In conclusion, we always want to double check our code to make sure that we don't exceed one string's bounds in our programs.
Assignment
Follow the Coding Tutorial and let's practice with string bounds!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
