Swift Break & Continue
Sometimes you need to change the normal flow of a loop: stop it early, or skip one round. Swift gives you two control transfer statements for that:
| Statement | Effect |
|---|---|
break |
leaves the loop (or switch) immediately |
continue |
skips the rest of the current iteration and starts the next one |
break label / continue label |
does the same for an outer labelled loop |
break
break ends the loop right away. A typical use is stopping as soon as you have found what you were looking for:
let numbers = [4, 8, 15, 16, 23, 42]
for n in numbers {
if n % 2 != 0 {
print("First odd number: \(n)")
break
}
print("\(n) is even, keep looking…")
}4 is even, keep looking…
8 is even, keep looking…
First odd number: 15
The numbers after 15 are never visited.
continue
continue skips the remaining statements of this iteration only. The loop itself keeps going:
let words = ["swift", "", "is", "", "fun"]
var sentence: [String] = []
for word in words {
if word.isEmpty {
continue // ignore empty entries
}
sentence.append(word.uppercased())
}
print(sentence.joined(separator: " "))SWIFT IS FUN
break and continue in while loops
Both statements work in while and repeat-while loops too. A common pattern is an "endless" loop that exits with break once a condition inside is met:
var n = 0
while true {
n += 1
if n % 3 == 0 {
continue // skip multiples of 3
}
if n > 10 {
break // stop after 10
}
print(n, terminator: " ")
}
print()1 2 4 5 7 8 10
Tip: With
continuein awhileloop, make sure the counter is updated before thecontinue, otherwise you can create an infinite loop.
break inside switch
In a switch, break ends the switch statement. Because Swift cases don't fall through, you mostly use it to mark a case that intentionally does nothing:
let commands = ["start", "noop", "stop", "jump"]
for command in commands {
switch command {
case "start":
print("Starting engine")
case "stop":
print("Stopping engine")
case "noop":
break // do nothing
default:
print("Unknown command: \(command)")
}
}Starting engine
Stopping engine
Unknown command: jump
Note that this break only leaves the switch, not the surrounding for loop — the next command is still processed.
Labelled statements
When loops are nested, a plain break only leaves the innermost loop. Give the outer loop a label (a name followed by a colon) to break out of both at once:
let grid = [
[1, 2, 3],
[4, -1, 6],
[7, 8, 9]
]
search: for (r, row) in grid.enumerated() {
for (c, value) in row.enumerated() {
if value < 0 {
print("Found a negative value at row \(r), column \(c)")
break search
}
print("Checked \(value)")
}
}
print("Search finished")Checked 1
Checked 2
Checked 3
Checked 4
Found a negative value at row 1, column 1
Search finished
continue outerLabel works the same way: it jumps to the next iteration of the labelled loop. Labels are also handy to leave a loop from inside a switch:
let input = [3, 5, 0, 7]
reading: for value in input {
switch value {
case 0:
print("Got 0 — end of input")
break reading
default:
print("Value \(value)")
}
}Value 3
Value 5
Got 0 — end of input
Test yourself
What does continue do inside a for-in loop?
- Ends the loop completely
- Skips to the next iteration
- Restarts the loop from the first element
- Pauses the program
Inside a switch that is inside a for loop, what does a plain break leave?
- The for loop
- The whole program
- Only the switch
- Nothing — it's an error
How do you leave two nested loops at once?
- break break
- Label the outer loop and use
break label - Use
returnonly - Use
fallthrough