If-Else Statements
In this page:
Basic if Statement
An if statement runs its block of code only when the condition inside the parentheses-free header evaluates to true.
Example: Basic if Statement
let temperature = 30
if temperature > 25 {
print("It is hot outside")
}
Login to try C/C++/Java/PHP code in the editor
if-else
Adding an else clause provides a fallback block that runs when the if condition is false.
Example: if-else
let temperature = 15
if temperature > 25 {
print("It is hot outside")
} else {
print("It is not that hot")
}
Login to try C/C++/Java/PHP code in the editor
else if Chains
Multiple conditions can be checked in order using else if, stopping at the first one that is true.
Note: Swift requires curly braces around every branch body, even a single-line one.
Example: else if Chains
let score = 72
if score >= 90 {
print("Grade: A")
} else if score >= 70 {
print("Grade: B")
} else {
print("Grade: C or below")
}
Login to try C/C++/Java/PHP code in the editor
- Wrapping the condition in parentheses like
if (x > 5), which is unnecessary and not idiomatic Swift (though harmless). - Forgetting the curly braces around a single-statement body; Swift requires them, unlike some C-style languages.
- Chaining many separate
ifstatements when a singleelse ifchain (orswitch) would be clearer.
ifexecutes a block only when its condition is true.else ifchecks additional conditions in sequence, andelseruns when none matched.- Curly braces
{ }are mandatory in Swift, even for a single statement. - Conditions must be actual
Boolexpressions -- Swift will not accept anIntas a condition.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: