Start learning free

LESSON 114 OF 415 · FOR LOOPS - LOOPING OVER ARRAYS

The For Loop and Execution Flow in Swift

Lesson Read the full explanation

Swift uses the brackets ({}) to indicate which lines of code are part of a for loop and which are not.

Take this code for example:

let languages = ["Python", "Java", "JavaScript"]

for language in languages {
  print("I love \(language)")
  print("I want to get better at it")
}

Both print statements are part of the loop since they are written inside the brackets.

This means that both messages will be printed for every language in the languages array. The output of that code would be:

I love Python
I want to get better at it
I love Java
I want to get better at it
I love JavaScript
I want to get better at it

As for this code:

let languages = ["Python", "Java", "JavaScript"]

for language in languages {
  print("I love \(language)")
}
print("I want to get better at them")

The print("I want to get better at them") is not part of the loop.

This means that only print("I love \(language)") will be executed for every language in the languages array.

Then, when the for loop is over, the print("I want to get better at them") will be executed only once.

The output of this program would be:

I love Python
I love Java
I love JavaScript
I want to get better at them

Execution flow

Lastly, note that the execution of a program always begins on the first line. The code is then executed one line at a time from top to bottom. This is known as execution flow and is the order a program in Swift executes code.

For example, this program:

let fruits = ["banana", "apple", "kiwi"]

print("I'm hungry!")

for fruit in fruits {
  print("I'm gonna eat:")
  print(fruit)
}


print("I love my life!")

prints:

I'm hungry!
I'm gonna eat:
banana
I'm gonna eat:
apple
I'm gonna eat:
kiwi
I love my life!


Assignment:

Add a for loop inside our code in the editor such that the final program would print:

Today we'll learn about:
Python
Java
JavaScript
Let's code!
STEP 1 OF 1
    Ctrl + Enter to check

    SWIFT · FOR LOOPS - LOOPING OVER ARRAYS

    Exercise Create A For Loop in Swift, explained

    What a for loop does

    A for loop runs a block of code once for every element of a sequence. In Swift the usual form is for-in: you name a loop variable, say which array to walk through, and put the repeated code between braces.

    let languages = ["Python", "Java", "JavaScript"]
    
    for language in languages {
        print("I love \(language)")
    }
    

    On the first pass language is "Python", on the second "Java", on the third "JavaScript". No counter or index is needed: Swift hands you each element directly. The loop variable is a constant that exists only inside the braces.

    Braces decide what repeats

    Swift uses the braces to mark which lines belong to the loop. Every statement inside them runs once per element. Anything after the closing brace runs once, when the loop is over.

    let languages = ["Python", "Java", "JavaScript"]
    
    for language in languages {
        print("I love \(language)")
        print("I want to get better at it")
    }
    

    Both print calls are inside, so the output alternates:

    I love Python
    I want to get better at it
    I love Java
    I want to get better at it
    I love JavaScript
    I want to get better at it
    

    Now move the second call after the closing brace:

    for language in languages {
        print("I love \(language)")
    }
    print("I want to get better at them")
    
    I love Python
    I love Java
    I love JavaScript
    I want to get better at them
    

    Indentation helps a human reader, but Swift looks only at the braces. A line that is indented but sits after the closing brace is still outside the loop.

    Execution flow

    A program starts at its first line and runs one line at a time, from top to bottom. This order is called the execution flow. A loop does not break the flow. When the flow reaches the loop, it runs the body once per element, and when the elements are used up it continues with the line after the closing brace.

    let fruits = ["banana", "apple", "kiwi"]
    
    print("I'm hungry!")
    
    for fruit in fruits {
        print("I'm gonna eat:")
        print(fruit)
    }
    
    print("I love my life!")
    
    I'm hungry!
    I'm gonna eat:
    banana
    I'm gonna eat:
    apple
    I'm gonna eat:
    kiwi
    I love my life!
    

    The first message prints once because it comes before the loop. The two lines inside print three times, and the last message prints once because it comes after.

    The exercise

    The editor holds this starting code:

    let languages = ["Python", "Java", "JavaScript"]
    
    print("Today we'll learn about:")
    
    // Write the for loop below:
    
    
    print("Let's code!")
    

    The program must print the heading, then each language on its own line, then Let's code!. The steps are:

    1. Write the loop header between the two existing print calls: for language in languages {. The variable must be named language.
    2. Print the loop variable inside the braces with print(language). Each pass prints one name, and print ends its output with a newline, so every name lands on its own line.
    3. Close the brace before the last print. That keeps Let's code! outside the loop, so it runs once, after the final language.

    The finished program:

    let languages = ["Python", "Java", "JavaScript"]
    
    print("Today we'll learn about:")
    
    // Write the for loop below:
    for language in languages {
        print(language)
    }
    
    print("Let's code!")
    

    Common mistakes

    • Printing the heading inside the loop. It would appear three times.
    • Forgetting the closing brace. The compiler reports an error at the end of the file, because the loop is never closed.
    • Printing the array itself. print(languages) shows ["Python", "Java", "JavaScript"] on one line, not one name per line.
    • Adding parentheses around the header. Swift does not need them: write for language in languages.

    Key takeaways

    • for item in array visits every element, with no index.
    • The braces mark the loop body. Statements inside run once per element, statements after run once.
    • A program runs top to bottom, and a loop repeats its body in place before the flow moves on.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free