If-Else Statements
An if-else statement lets your program make a decision, like choosing one path if something is true and another path if it's not.
In this page:
Syntax
if condition {
// runs when true
} else if otherCondition {
// runs when this is true
} else {
// fallback
}
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
// Declare a constant `temperature`, set to `30`
let temperature = 30
// Check whether `temperature > 25`
if temperature > 25 {
// Print "It is hot outside" to the console
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
// Declare a constant `temperature`, set to `15`
let temperature = 15
// Check whether `temperature > 25`
if temperature > 25 {
// Print "It is hot outside" to the console
print("It is hot outside")
// Otherwise, run this branch
} else {
// Print "It is not that hot" to the console
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
// Declare a constant `score`, set to `72`
let score = 72
// Check whether `score >= 90`
if score >= 90 {
// Print "Grade: A" to the console
print("Grade: A")
// Otherwise, if `score >= 70`, run this branch
} else if score >= 70 {
// Print "Grade: B" to the console
print("Grade: B")
// Otherwise, run this branch
} else {
// Print "Grade: C or below" to the console
print("Grade: C or below")
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- 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.
Chapter Summary
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: