With the break statement, we can prematurely terminate a loop from inside that loop.
When Swift reaches the break statement, it's going to immediately terminate the loop without checking any conditions.
Breaking a for loop:
In this example, we will terminate the loop when we find a "banana" in our array:
let fruits = ["kivi", "orange", "banana", "apple", "pear"]
for fruit in fruits {
print(fruit)
if fruit == "banana" {
break
}
}
The output of this code is:
kivi
orange
banana
As you can see, our program doesn't print apple and pear.
Here's what happens during this loop:
1. First iteration:
a. fruit = "kivi"
b. print(fruit) // Output: kivi
c. Is fruit == "banana"? No.
2. Second iteration:
a. fruit = "orange"
b. print(fruit) // Output: orange
c. Is fruit == "banana"? No.
3. Third iteration:
a. fruit = "banana"
b. print(fruit) // Output: banana
c. Is fruit == "banana"? Yes:
break => Exit the loop immediately
Here's the same program but iterating through the array with indices instead:
let fruits = ["kivi", "orange", "banana", "apple", "pear"]
for i in 0..<fruits.count {
print("Index \(i): \(fruits[i])")
if fruits[i] == "banana" {
break
}
}
The output of this code is:
Index 0: kivi
Index 1: orange
Index 2: banana
As you can see, our program doesn't print apple and pear.
Assignment
Let's print all the lessons our student finished!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.