Start learning free

LESSON 110 OF 415 · FOR LOOPS - LOOPING OVER ARRAYS

Why For Loops in Swift: Repeating Work Without Repeating Code

Lesson Read the full explanation

For loops are very useful for iterating over sequences of elements.

To understand the value of for loops, let's take some time to see how frustrating our life would be if a repeated task required us to type out the same code every single time.


Example: Greeting our friends

Imagine this: We have an array of friends and we want to greet each of them using a message template.

If we only use print(), our program might look like this:

let friends = ["Andy", "Mircea", "David", "Mary"]

print("Hey, " + friends[0])
print("Hey, " + friends[1])
print("Hey, " + friends[2])
print("Hey, " + friends[3])

That's ugly, but still manageable. After all, we're writing only 4 lines of code and most probably copying and pasting a few times.

Now imagine if we had 10, 100 friends? It would take an extremely long time and by the end, we could still end up with inconsistencies and mistakes.

We'll learn how for loops come to our rescue in the next lesson. But for now, let's gain an appreciation for them.


Assignment
Follow the Coding Tutorial to see how frustrating our life is without for loops.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    SWIFT · FOR LOOPS - LOOPING OVER ARRAYS

    Why For Loops in Swift, explained

    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:

    1. Print "I eat " + fruits[0], which gives I eat banana.
    2. 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 after I eat is part of the text in quotes. Without it you would get I eatbanana.
    • Going past the end crashes. fruits[4] compiles, but the program stops at run time, because the last valid index is fruits.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.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free