Control Flow
If Else
if, else if, and else choose one branch based on Boolean conditions.
Choose a branch
if_else.swift
Replay: real traced execution (multi-file project)
let score = 74
var band = "needs practice"
if score >= 90 {
band = "excellent"
} else if score >= 70 {
band = "steady"
} else {
band = "needs practice"
}
print("score=\(score)")
print("band=\(band)")
let score = 58
var band = "needs practice"
if score >= 90 {
band = "excellent"
} else if score >= 70 {
band = "steady"
} else {
band = "needs practice"
}
print("score=\(score)")
print("band=\(band)")
let score = 91
var band = "needs practice"
if score >= 90 {
band = "excellent"
} else if score >= 70 {
band = "steady"
} else {
band = "needs practice"
}
print("score=\(score)")
print("band=\(band)")
score ← 74, band ← needs practice
1let score→ 74 = 74 //@score=91, 582var band→ needs practice = "needs practice"if score >= 70
5 band = "excellent"6} else if score74 >= 70 {7 band = "steady"8} else {print("score=\(score)")
12print("score=\(score74)")13print("band=\(bandsteady)")outputscore=74 band=steady
score ← 58, band ← needs practice
1let score→ 58 = 582var band→ needs practice = "needs practice"print("score=\(score)")
12print("score=\(score58)")13print("band=\(bandneeds practice)")outputscore=58 band=needs practice
score ← 91, band ← needs practice
1let score→ 91 = 912var band→ needs practice = "needs practice"if score >= 90
4if score91 >= 90 {5 band = "excellent"6} else if score >= 70 {print("score=\(score)")
12print("score=\(score91)")13print("band=\(bandexcellent)")outputscore=91 band=excellent
Choose the Band
scorestarts at74.- The first check,
score >= 90, is false. - The next check,
score >= 70, is true. bandbecomessteady. | Score | First matching branch | Band | | --- | --- | --- | |91|score >= 90|excellent| |74|score >= 70|steady| |58|else|needs practice|
branching
An `if` chain tests conditions in order. Swift runs the first branch whose condition is true and skips the rest.
Exercise: if_else.swift
Use if, else if, and else to map a score to excellent, steady, or needs practice