The problem: the same line again and again
Programs often do the same thing for every element of an array. Without a loop, the only tool is to write the same statement once per element. Here is an array of friends and one greeting per friend:
let friends = ["Andy", "Mircea", "David", "Mary"]
print("Hey, " + friends[0])
print("Hey, " + friends[1])
print("Hey, " + friends[2])
print("Hey, " + friends[3])
Hey, Andy
Hey, Mircea
Hey, David
Hey, Mary
Each line reads one element by its index and joins it to a fixed piece of text with +. Indexes start at 0, so four friends use friends[0] to friends[3].
With four friends this is annoying but fine. The trouble grows with the data, and it shows up in several ways:
- Length. A hundred friends means a hundred lines, and a million means a million.
- Mistakes. After many copies and pastes, it is easy to leave one index out, repeat one, or forget to change a number. The compiler will not notice.
- Changes. If the greeting should become
"Hello, ", you must edit every line. - Unknown size. If the array comes from elsewhere, you don't know how many lines to write. If you write too many, the program crashes with an index out of range error. If you write too few, some friends are skipped.
A for loop fixes all of these. It lets you write the statement once and have Swift run it for each element, however many there are. The next lesson shows the syntax. This one shows the repetition the loop will replace.
The exercise
The starter code has an array of four fruits. The task is to print I eat followed by each fruit, one line per fruit, using only print:
- Print
"I eat " + fruits[0], which givesI eat banana. - Do the same for indexes 1, 2 and 3.
let fruits = ["banana", "orange", "pear", "kiwi"]
print("I eat " + fruits[0])
print("I eat " + fruits[1])
print("I eat " + fruits[2])
print("I eat " + fruits[3])
I eat banana
I eat orange
I eat pear
I eat kiwi
Notice that the four lines differ only in one number. That is the pattern a loop removes.
Details worth knowing
- The
+operator joins strings. The space afterI eatis part of the text in quotes. Without it you would getI eatbanana. - Going past the end crashes.
fruits[4]compiles, but the program stops at run time, because the last valid index isfruits.count - 1, which is 3. - String interpolation is the other way to build the text.
print("I eat \(fruits[0])")prints the same line. The loop lessons use this form.
What happens when the array changes
Suppose a fifth friend is added to friends. The four print lines still compile and run, but the new friend is never greeted, and nothing tells you. Suppose instead one friend is removed. Now friends[3] points past the end, and the program crashes at run time. In both cases the code and the data have drifted apart, and the repeated lines are what made that possible. A loop reads the array's own length every time, so it cannot drift.
Key takeaways
- Handling each array element by hand means one line per element, which is long, error-prone and impossible when the size isn't known.
- Array indexes start at 0 and end at
count - 1. - A for loop runs one statement once for every element, so the code stays the same size however long the array is.
