Coding for All
Lesson 19: While Loops
While Loops Count down to lift-off with while.
1var countdown = 3
2while countdown > 0 {
3 print(countdown)
4 countdown = countdown - 1
5}
6print("Lift off!")
Terminal
$ swift main.swift
3
2
1
Lift off!
Every line, explained
var countdown = 3
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 countdown > 0 {
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. Here it keeps going while countdown is greater than 0, and like if, no round brackets needed.
print(countdown)
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. Prints 3, then 2, then 1.
countdown = countdown - 1
Takes 1 off countdown each trip. Without this line the loop would never end!
}
This } closes the while loop.
print("Lift off!")
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. Outside the loop: it runs once, after the loop has finished.