Start learning free

LESSON 109 OF 349 · FOR LOOPS - LOOPING OVER ARRAYS

For Loop - Execution Flow in Swift in Swift

Lesson

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 list. 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 list.

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

    Exercise Create A For Loop 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