Foundations
Conditionals
An if statement chooses which block runs after checking a Boolean condition.
Choose a label
conditionals.swift
Replay: real traced execution (multi-file project)
let temperature = 72
let label: String
if temperature >= 80 {
label = "hot"
} else if temperature >= 60 {
label = "warm"
} else {
label = "cool"
}
print("temperature=\(temperature)")
print("label=\(label)")
let temperature = 48
let label: String
if temperature >= 80 {
label = "hot"
} else if temperature >= 60 {
label = "warm"
} else {
label = "cool"
}
print("temperature=\(temperature)")
print("label=\(label)")
let temperature = 91
let label: String
if temperature >= 80 {
label = "hot"
} else if temperature >= 60 {
label = "warm"
} else {
label = "cool"
}
print("temperature=\(temperature)")
print("label=\(label)")
temperature ← 72
1let temperature→ 72 = 72 //@temperature=48, 912let label: Stringif temperature >= 60
5 label = "hot"6} else if temperature72 >= 60 {7 label = "warm"8} else {print("temperature=\(temperature)")
12print("temperature=\(temperature72)")13print("label=\(labelwarm)")outputtemperature=72 label=warm
temperature ← 48
1let temperature→ 48 = 482let label: Stringprint("temperature=\(temperature)")
12print("temperature=\(temperature48)")13print("label=\(labelcool)")outputtemperature=48 label=cool
temperature ← 91
1let temperature→ 91 = 912let label: Stringif temperature >= 80
4if temperature91 >= 80 {5 label = "hot"6} else if temperature >= 60 {print("temperature=\(temperature)")
12print("temperature=\(temperature91)")13print("label=\(labelhot)")outputtemperature=91 label=hot
Follow the Branch
temperaturestarts at72.- Swift first checks whether
temperature >= 80. 72is below80, so it checkstemperature >= 60.- That check is true, so
labelbecomeswarm. - The program prints
temperature=72andlabel=warm. | temperature | path | label | | --- | --- | --- | | 48 | below 60 | cool | | 72 | at least 60 | warm | | 91 | at least 80 | hot |
if else
Use `if` for the true branch and `else` for the fallback branch.
Exercise: conditionals.swift
Reproduce label=warm for temperature 72, then try 48 and 91 and predict the label before running each one.