Swift conditionals: the if statement

By

Published · Updated

Tagged: Swift

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 statements are the most popular way to perform a conditional check. We use the if keyword followed by a boolean expression, followed by a block containing code that runs if the condition is true:

let condition = true
if condition == true {
    // code executed if the condition is true
}

An else block is executed if 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
}

You can optionally wrap the condition validation into parentheses if you prefer:

if (condition == true) {
    // ...
}

Swift does not need the parentheses, and most Swift code leaves them out.

And you can also just write:

if condition {
    // runs if `condition` is `true`
}

or

if !condition {
    // runs if `condition` is `false`
}

condition is already a Bool. Comparing it to true adds nothing.

A realistic example

Here is 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.

The condition must be an actual Bool. You cannot write if age with a number, like you would in JavaScript. Write if age >= 18 instead.

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.

No assignment in a condition

One thing that separates Swift from many other languages is that it prevents bugs caused by erroneously doing an assignment instead of a comparison. This means you can’t do this:

if condition = true {
    // The program does not compile
}

and the reason is that the assignment operator does not return anything, but the if conditional must be a boolean expression.

Since Swift 5.9, if can also be an expression that produces a value. Each branch must be a single expression, and you need an else:

let message = if condition { "yes" } else { "no" }

Want me to talk about your product? You can sponsor this site.

Related posts about swift: