Coding for All
Lesson 20: Break
Break Escape from a loop with break.
1var count = 0
2while true {
3 print(count)
4 count += 1
5 if count == 5 {
6 break
7 }
8}
Terminal
$ swift main.swift
0
1
2
3
4
Every line, explained
var count = 0
var creates a variable: a box whose value CAN change. The Swift rule of thumb: use let unless you truly need to change the value. (Swift even warns you if a var never actually changes!)
while true {
A while loop repeats its block for as long as the condition is true. The condition is checked again before every trip around the loop. while true would repeat forever, because the condition is always true! We will need break to escape.
print(count)
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. All lowercase, both brackets needed, and no semicolon at the end; Swift doesn't use them.
count += 1
Adds 1 to count. Fun fact: Swift has NO ++ operator (it was removed from the language!), so Swift people write count += 1.
if count == 5 {
if checks a condition. Swift style: no round brackets around the condition, but the curly braces { } are always required. Once the counter reaches 5, it is time to stop.
break
break immediately stops the loop it is inside; Swift jumps to the first line after the loop's closing brace.
}
This } closes the if block.
}
This } closes the while loop.