Start learning free

LESSON 68 OF 415 · CONDITIONAL STATEMENTS

If Statements in Swift: if and else

Lesson Read the full explanation

TL ; DR:

  • if statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:

    var isRainy = true
    if isRainy {
        print("I bring an umbrella")
    }
    



Full lesson:

As humans, we often make decisions based on conditions. For example, we might go through these decision-making processes during a day:

If it's rainy:
  I bring an umbrella

If I'm hungry:
  I have breakfast

If I'm tired:
  I take a nap

We can also tell the computer to make decisions like these in our programs.


If Statements:

if statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:

if conditions {
    // instructions
}

The keyword if tells Swift to execute the code inside the curly braces (where we have our Swift comment) only if the conditions defined after if (no parentheses needed in Swift) are met.


Boolean conditions:

The conditions inside if statements are known as Boolean conditions and they may only be true or false.

If the boolean condition evaluates to true, the program executes the statements inside curly braces. If it evaluates to false, the statements will not execute.

If you check our example, you'll see that all the conditions there (it's rainy, I'm hungry and I'm tired) are Boolean conditions.

Let's turn those decisions into working code using if statements:

var isRainy = true
if isRainy {
    print("I bring an umbrella")
}

The code above prints "I bring an umbrella" since the condition isRainy evaluates to true

But this code:

var amHungry = false
if amHungry {
    print("I have breakfast")
}

prints nothing since amHungry evaluates to false.


Assignment
Follow the Coding Tutorial and let's practice with if statements!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    SWIFT · CONDITIONAL STATEMENTS

    If Statements in Swift, explained

    Making decisions in code

    People decide things from conditions: if it is raining, take an umbrella; if you are hungry, eat. An if statement lets a program do the same. It runs a block of code only when a condition is true.

    var isRainy = true
    if isRainy {
        print("I bring an umbrella")
    }
    
    I bring an umbrella
    

    The general shape is:

    if condition {
        // runs only when the condition is true
    }
    

    After the keyword if comes the condition, then a block in curly braces. Swift doesn't need parentheses around the condition, although if (isRainy) { ... } is also accepted. The braces are required, even for a single line, so if isRainy print("...") is a compile error.

    Boolean conditions

    The condition must be a Bool, a value that is either true or false. When it is true, the block runs. When it is false, the block is skipped and the program continues after the closing brace:

    var amHungry = false
    if amHungry {
        print("I have breakfast")
    }
    print("done")
    
    done
    

    Nothing is printed for the if, because amHungry is false, but the later print still runs.

    Swift is strict here. A number is not a condition. This code doesn't compile:

    let flag = 1
    if flag {
        print("yes")
    }
    
    error: type 'Int' cannot be used as a boolean; test for '!= 0' instead
    

    Write the comparison out instead, for example flag != 0. Comparisons like n > 3 and name == "Ann" are expressions that produce a Bool, so they work directly as conditions. A condition that is already a Bool needs no == true.

    Adding else

    An else block runs when the condition is false. It takes no condition of its own, because it covers every case the if didn't. Exactly one of the two blocks runs:

    let passed = false
    if passed {
        print("Passed the test")
    } else {
        print("Failed")
    }
    
    Failed
    

    The closing brace of the if block, the word else and the opening brace of the else block usually share a line: } else {. To test further conditions in order, chain them with else if:

    let n = 5
    if n > 8 {
        print("big")
    } else if n > 3 {
        print("medium")
    } else {
        print("small")
    }
    
    medium
    

    Combining conditions

    Three operators build bigger conditions out of smaller ones: && (and) is true when both sides are true, || (or) is true when at least one side is, and ! (not) flips a value:

    let age = 20
    let hasTicket = true
    if age >= 18 && hasTicket {
        print("welcome")
    }
    if age < 18 || !hasTicket {
        print("stop")
    } else {
        print("ok")
    }
    
    welcome
    ok
    

    The first condition holds because both parts are true. In the second, age < 18 is false and !hasTicket is false, so the else block runs. Both operators stop early: if the left side of && is false, the right side is never evaluated.

    The exercise

    The starter code declares let passed: Bool = true. The task has three steps:

    1. Write if passed {. The constant is already a Bool, so it is the whole condition.
    2. Inside the block, print "Passed the test".
    3. Close with } else {, print "Failed", and close the block with }.
    let passed: Bool = true
    if passed {
        print("Passed the test")
    } else {
        print("Failed")
    }
    
    Passed the test
    

    With passed set to false, the same code prints Failed.

    Common mistakes

    • Using = instead of ==. if n = 3 is rejected with use of '=' in a boolean context, did you mean '=='?.
    • Leaving out the braces. They are mandatory in Swift.
    • Using a non-Bool condition. Integers, strings and optionals must be compared or unwrapped first.
    • Putting a condition on else. Use else if for that.
    • Starting a new line before else. It is accepted by the compiler, but keeping } else { together is the common style.

    Key takeaways

    • if condition { ... } runs the block only when the condition is true.
    • The condition must be a Bool, and parentheses around it are optional.
    • else covers the case where the condition is false, and else if adds more conditions.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free