Making decisions
Chapter 2 ended with a comparison. It gave you a Bool, but the program
printed the answer and carried on. Now we can use that answer to choose which
lines run.
if needs a Bool. A number such as temperature isn’t one by itself.
Give it the comparison:
let temperature = 22.5
if temperature > 22 {
print("Warmer than 22.")
}
if temperature > 23 {
print("Warmer than 23.")
} else {
print("Not warmer than 23.")
}
Warmer than 22.
Not warmer than 23.
The first condition is true, so its block prints. The second is false,
so the else block prints instead. There are no parentheses around either
condition; the braces mark the blocks. An if doesn’t need an else when
there’s nothing to do for the other answer.
Checking again
if checks once. while checks before each pass through its block:
var page = 1
while page < 4 {
print("Page \(page)")
page = page + 1
}
Page 1
Page 2
Page 3
The first check finds page at 1. Each pass prints it and moves it along.
Once page reaches 4, the condition is false, so the block does not run
again. Without that change to page, this loop would keep going.
A known number of passes
When you already know which whole numbers you want, for … in can walk a
range instead:
for page in 1...3 {
print("Full: \(page)")
}
for page in 1..<3 {
print("Short: \(page)")
}
Full: 1
Full: 2
Full: 3
Short: 1
Short: 2
1...3 includes 3. The half-open 1..<3 stops before it, giving the
second loop one fewer page. You needn’t change page yourself; the loop
visits each number in the range.
Skip one, or stop
A loop needn’t use every value. Here, page 2 is skipped and the loop
stops when it reaches page 5:
for page in 1...6 {
if page == 2 {
continue
}
if page == 5 {
break
}
print("Keep page \(page)")
}
Keep page 1
Keep page 3
Keep page 4
continue starts the next pass through the loop without running the rest
of this one. break leaves the loop altogether, so page 6 is never
visited. In a nested loop, each affects the nearest loop. Try changing
page == 5 to page == 4 and see where the output stops.