Skip to content

Swift Conditionals: `if`

New Course Coming Soon:

Get Really Good at Git

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 ran 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
}

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

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my Swift Handbook

Here is how can I help you: