What break does
The break statement ends a loop from the inside. When Swift reaches it, the loop stops at once, without finishing the current iteration and without checking the loop's condition again. The program continues with the first statement after the loop.
Use it when the rest of the work is pointless, for example once you have found the element you were looking for.
Breaking a for-in loop
This loop prints fruits until it has printed a banana:
let fruits = ["kivi", "orange", "banana", "apple", "pear"]
for fruit in fruits {
print(fruit)
if fruit == "banana" {
break
}
}
It prints:
kivi
orange
banana
The first two iterations fail the if test and finish normally. On the third, fruit is "banana", the condition is true, and break leaves the loop. "apple" and "pear" are never visited.
The position of break relative to print matters. Here the print comes first, so the banana is printed. With the if placed before the print, the loop would stop before printing it.
Breaking a loop over indices
It works the same way when the loop runs over positions:
let fruits = ["kivi", "orange", "banana", "apple", "pear"]
for i in 0..<fruits.count {
print("Index \(i): \(fruits[i])")
if fruits[i] == "banana" {
break
}
}
Index 0: kivi
Index 1: orange
Index 2: banana
Finding the first match
A typical use is a search that records where something was found and then stops. This loop looks for the first negative number:
let nums = [3, -1, 4, -5, 9]
var found: Int? = nil
for (i, v) in nums.enumerated() {
if v < 0 {
found = i
break
}
}
print(found as Any)
It prints Optional(1). The second negative number, -5, is never examined, because the loop ended at the first one. Without break, found would end up holding 3, the position of the last negative number. The variable is an optional, Int?, so it can stay nil when nothing matches.
Swift details
- Only the innermost loop ends. In nested loops,
breakleaves the loop that directly contains it. To leave an outer loop, give it a label and name it:outer: for i in 0..<3 { for j in 0..<3 { if j == 1 { break outer } } }. breakinsideswitchbelongs to the switch. In aswitchcase,breakends the switch, not the loop around it. A case with no work to do must contain at least one statement, andbreakserves for that.- Braces are required. An
ifbody needs braces even for one statement, and the condition needs no parentheses. - String comparison uses
==.fruit == "banana"compares the text.
The exercise
The code starts with two constants:
let lessons = ["variables", "conditionals", "arrays", "functions", "loops"]
let lastFinishedLesson = "functions"
The task is to print every lesson the student finished, which means every lesson up to and including lastFinishedLesson.
- Loop over the array.
for lesson in lessonsgives each lesson in order. No index is needed. - Print first.
print("Finished " + lesson)joins the two strings, so the last finished lesson is printed too. - Then test and break. If
lesson == lastFinishedLesson, callbreak. The remaining lessons are not visited.
let lessons = ["variables", "conditionals", "arrays", "functions", "loops"]
let lastFinishedLesson = "functions"
for lesson in lessons {
print("Finished " + lesson)
if lesson == lastFinishedLesson {
break
}
}
The output is:
Finished variables
Finished conditionals
Finished arrays
Finished functions
Common mistakes
- Putting the check before the print. The loop stops before the last finished lesson is printed, so
"Finished functions"is missing. - Breaking without a condition. A bare
breakat the end of the body stops the loop after the first iteration. - Expecting
breakto leave two loops. It leaves only the innermost one unless you use a label.
Key takeaways
breakends the loop immediately and execution continues after it.- Code placed before
breakin the body runs on the last iteration; code after it does not. - Use a labeled loop to break out of an outer loop.
