Control flow
Swift conditionals: the if statement
Learn how to use if and else conditionals in Swift, write boolean conditions cleanly, and why Swift prevents the bug of assigning instead of comparing.
This tutorial belongs to the Swift series
if is the most common way to make a decision in code. You write the if keyword, a boolean expression, and a block of code that runs only when the expression is true:
let condition = true
if condition == true {
// code executed if the condition is true
}
Add an else block to run something when the condition is false:
let condition = true
if condition == true {
// code executed if the condition is true
} else {
// code executed if the condition is false
}
Writing the condition
You can wrap the condition in parentheses if you like the look:
if (condition == true) {
// ...
}
Swift doesn’t need them, and most Swift code leaves them out. And since condition is already a Bool, comparing it to true adds nothing. You can write:
if condition {
// runs if `condition` is `true`
}
or negate it with !:
if !condition {
// runs if `condition` is `false`
}
A realistic example
Here’s how it looks with a real value:
let age = 17
if age >= 18 {
print("You can vote")
} else {
print("Not yet")
}
This prints Not yet.
Chaining with else if
When there are more than two outcomes, chain conditions with else if:
let temperature = 34
if temperature < 12 {
print("Bring a jacket")
} else if temperature > 30 {
print("Stay hydrated")
} else {
print("Nice weather")
}
Swift checks the conditions from top to bottom and runs the first block whose condition is true. Then it skips the rest. Here it prints Stay hydrated.
If a chain grows past three or four branches, a switch is usually cleaner. That’s the next lesson.
The condition must be a Bool
In Swift the condition must be an actual Bool. You can’t write if count with a number, like you would in JavaScript. Write if count > 0 instead. It’s a few more characters, and it removes any doubt about what you’re checking.
No assignment in a condition
One thing that separates Swift from many other languages: it prevents the classic bug of typing = (assignment) when you meant == (comparison). This doesn’t compile:
if condition = true {
// The program does not compile
}
The assignment operator doesn’t return a value, and an if condition must be a boolean expression. So the compiler stops you before that typo reaches your users.
Lesson completed