AI Workshop: learn to build apps with AI →
Control Flow: If Statements

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


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 is run 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) {
    // ...
}

And you can also just write:

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

Or:

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

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
}

The reason is that the assignment operator does not return a value, but the if condition must be a boolean expression.

Lessons in this unit:

0: Introduction
1: ▶︎ If Statements
2: Switch Statements
3: Ternary Operator
4: For-In Loops
5: While Loops
6: Repeat-While Loops
7: Control Transfer Statements