Start learning free

LESSON 69 OF 415 · CONDITIONAL STATEMENTS

If-Else Statements in Swift

Lesson Read the full explanation

Many times in our life, not only we choose to do something if a condition is met, but also choose to do something different if that condition is not met. For example:

If I'm tired:
    I take a nap
Otherwise:
    I start coding

If-else Statements:

When a condition for an if statement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen.

With an else statement, we can have an alternate block of code to be executed. For example:

var amTired = false
if amTired {
    print("I take a nap")
} else {
    print("I start coding")
}

The code above prints "I start coding" since the expression inside the if evaluates to false and so Swift will enter the else statement and execute the code inside it.

An else statement cannot exist without a corresponding if statement. This combination is refered to as an if-else statement.


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


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    SWIFT · CONDITIONAL STATEMENTS

    If Else in Swift, explained

    What an if-else statement does

    An if statement runs a block of code only when a condition is true. When the condition is false, the program skips the block and carries on, so nothing is reported. An else branch gives the program something to do in that second case. Exactly one of the two blocks runs, never both and never neither.

    In everyday terms: if I'm tired, I take a nap; otherwise, I start coding. Swift writes it like this:

    var amTired = false
    if amTired {
        print("I take a nap")
    } else {
        print("I start coding")
    }
    

    Because amTired is false, the program prints I start coding. Change the value to true and it prints I take a nap instead.

    The syntax

    A few rules apply to every Swift if:

    • The condition has no parentheses. You can add them, as in if (amTired) {, and the code still compiles, but idiomatic Swift leaves them out.
    • The braces are required. Even when the body is a single statement, Swift needs { and }. A body without braces is a compile error.
    • The condition must be a Bool. Swift does not treat numbers as true or false. With let count = 1, writing if count { fails with type 'Int' cannot be used as a boolean; test for '!= 0' instead. Write the comparison you mean, such as count != 0.
    • else has no condition. It runs whenever the if condition is false, so you never write a test after it.
    • else belongs to an if. It can't appear on its own, only attached to the closing brace of the if block before it.

    The usual style puts else on the same line as the closing brace: } else {. Swift ignores line breaks here, so this also compiles with else on its own line, but the one-line form is what Swift code normally looks like.

    The exercise

    The starting code declares passed as a Bool set to false and prints Passed the test when it is true. With the value false, the program prints nothing at all. The task is to attach an else branch that prints Failed the test, so the program reports a result either way.

    1. Find the closing brace of the if block, the } after the first print.
    2. Write else after it on the same line, followed by an opening brace: } else {.
    3. Add the print call for "Failed the test" inside the new block.
    4. Close the new block with its own }.

    The finished program:

    var passed: Bool = false
    if passed {
        print("Passed the test")
    } else {
        print("Failed the test")
    }
    

    It prints Failed the test. Setting passed to true makes it print Passed the test instead.

    Going further: more than two outcomes

    When there are more than two cases, chain the tests with else if. Swift checks the conditions from top to bottom and runs the first block whose condition is true. The final else catches whatever is left.

    let temperature = 15
    if temperature < 10 {
        print("cold")
    } else if temperature < 20 {
        print("mild")
    } else {
        print("warm")
    }
    

    This prints mild. The first test fails, the second passes, and the else is never reached.

    For a simple choice between two values, Swift also has the ternary operator condition ? a : b. With passed equal to true, let label = passed ? "yes" : "no" gives "yes". Use the full if-else when a branch does more than produce a value.

    Common mistakes

    • Writing = instead of ==. With var x = 3, the line if x = 5 { fails with use of '=' in a boolean context, did you mean '=='?. A single = assigns; == compares.
    • Giving else a condition. else (x > 3) { is not valid. To test something else, use else if.
    • Using a number as the condition. Compare it with a value instead of relying on it being zero or non-zero.
    • Forgetting that the branches are exclusive. If the if block runs, the else block is skipped entirely.

    Key takeaways

    • if runs a block when its condition is true; else runs a block when it is false.
    • The condition is a Bool with no parentheses, and the braces are always required.
    • Use else if to chain several tests, and finish with else for the remaining case.
    • Write } else { on one line, and use ==, not =, to compare.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free