Swift If Else
The if-else statement is Swift's primary tool for branching program flow based on Boolean conditions.
Basic if Statements
An if statement evaluates a Boolean expression and runs its body only when that expression is true. Unlike some languages, Swift requires the condition to be a genuine Bool — you cannot use an integer like 0 or 1 as a stand-in for true or false, which eliminates an entire class of accidental bugs.
A simple if statement
let temperature = 30
if temperature > 25 {
print("It's a hot day")
}
// Prints: It's a hot dayAdding else and else if
An else clause provides a fallback branch that runs when the if condition is false. When you have several mutually exclusive conditions to check in sequence, else if chains them together, and Swift evaluates each condition top to bottom, running only the first branch whose condition is true.
Chaining else if branches
let score = 82
if score >= 90 {
print("Grade: A")
} else if score >= 75 {
print("Grade: B")
} else if score >= 60 {
print("Grade: C")
} else {
print("Grade: F")
}
// Prints: Grade: BCombining Conditions
Logical operators let you combine multiple Boolean expressions into a single condition. The && (AND) operator requires both sides to be true, || (OR) requires at least one side to be true, and ! (NOT) inverts a Boolean value. Swift short-circuits && and ||, meaning the right-hand side is only evaluated if it is actually needed.
- && — true only when both operands are true
- || — true when at least one operand is true
- ! — inverts a Bool, turning true into false and vice versa
- Comparison operators (==, !=, <, >, <=, >=) produce the Bool values conditions are built from
- Parentheses group sub-conditions to control evaluation order explicitly
Combining conditions with && and ||
let age = 20
let hasID = true
if age >= 18 && hasID {
print("Entry allowed")
} else {
print("Entry denied")
}
let isWeekend = false
let isHoliday = true
if isWeekend || isHoliday {
print("No work today")
}if as an Expression
Traditionally if is a statement in Swift, but you can still capture a value from a branching decision using the ternary conditional operator condition ? valueIfTrue : valueIfFalse, which is a compact single-line alternative to a full if-else block when both branches simply produce a value.
Using the ternary operator
let count = 3
let label = count == 1 ? "item" : "items"
print("\(count) \(label)") // 3 items
let a = 7
let b = 12
let larger = a > b ? a : b
print(larger) // 12Exercise: Swift If Else
Are curly braces required around the body of an `if` statement in Swift, even for a single line?