break and continue
Prerequisites: while and repeat-while loops
Two keywords change how a loop runs:
breakstops the loop completely.continueskips the rest of the current pass and moves on to the next one.
Example
for n in 1...10 {
if n % 2 == 0 {
continue
}
if n > 7 {
break
}
print(n)
}
Expected output
1
3
5
7
Even numbers are skipped by continue. When n reaches 9, break
ends the loop.
Finding the first match
break is common when searching:
let temperatures = [18, 21, 26, 30, 24]
var firstHotDay: Int?
for (day, temp) in temperatures.enumerated() where temp > 25 {
firstHotDay = day + 1
break
}
if let firstHotDay {
print("First hot day: day \(firstHotDay)")
}
First hot day: day 3
A where clause on a for-in loop filters which items the body runs
for. (The Collections lessons show an even shorter way:
firstIndex(where:).)
Practice
Print the numbers from 1 to 20, skipping multiples of 3, and stop completely at 16.
Show solution
for n in 1...20 {
if n == 16 { break }
if n % 3 == 0 { continue }
print(n)
}