5️⃣Conditionals

Fall 2023 | Vin Bui

If we want to execute a chunk of code only when a condition is met, then in Swift, we can use if, else if, and else statements. Let’s take a look at the following example:

var a = 0
if a == 0 {
    print("Zero")
} else {
    print("Not Zero")
}

When using conditionals, we must provide a condition which is an expression that evaluates to true or false. To enclose a block of code in Swift, we use curly brackets ({ and }). In the example above, the expression a == 0 evaluates to true so the block of code containing print("Zero") will be executed.

Now, what if a == 0 evaluates to false? In that case, Swift will read for the next condition, if any. Because the next statement is an else statement, there is no condition to check so this block of code will be executed.

Sometimes, we want to check for multiple conditions? In that case, there is more than one option:

  1. Use the && (and) or || (or) operators

  2. Use an else if statement

Let’s take a look at the second option.

var a = -6
if a < 0 {
    print("Negative")
} else if a % 2 == 0 {
    print("Even")
} else {
    print("Not even or negative")
}

First, the expression a < 0 is evaluated. Since -6 < 0 evaluates to true, Swift executes the block of code containing print("Negative"). Now, since the next statement is an else if statement, it will not be executed. The reason is because this else if statement is connected to an if statement. Since the first if statement evaluated to true, Swift will not check any other statements that are connected.

Now, if we were to change the else if statement to an if statement, Swift will check this statement because it is no longer connected to the first if statement.

Because both conditions are met and they are not linked together, "Negative" and "Even" will both be printed.

Guard Statement

Sometimes we want to exit our code execution early on for efficiency purposes. This is where the guard statement comes in. A guard statement is similar to an if statement except an if statement runs when the condition is true while a guard statement runs when the condition is false. We can think of a guard statement as using an if statement with a “not equals” (!=) or not” (!) operator.

The format for a guard statement is as follows:

guard condition else {
    // block of code
    // control statement: return, break, continue, or throw
}

condition is an expression that evaluates to true or false. If true, then the block of code is not executed. If false, then the block of code is executed. This is the exact opposite of an if statement.

Last updated