Start learning free

LESSON 82 OF 415 · CONDITIONAL STATEMENTS

Chaining Conditionals in Swift: if, else if, else

Lesson Read the full explanation

Sometimes we can have more than two possible scenarios which need a different code to be ran. We can add else if statements to allow for as many outcomes as we want:

let language = "Python"
if language == "JavaScript" {
    print("It's super popular!")
} else if language == "Python" {
    print("It's so simple!")
} else if language == "Java" {
    print("It's pretty hardcore!")
} else {
    print("It's exotic!")
}

In the example above, language == "JavaScript" evaluates to false, so we move on and enter the following else if.

There, language == "Python" evaluates to true, so we execute what's inside that block and print "It's so simple!".

The rest of the conditions are not evaluated.

In case none of the conditions evaluates to true, then the code in the final else statement would execute. For example, if language was "Go", the program would have printed "It's exotic!"


Assignment
Follow the Coding Tutorial and let's write some chained conditionals.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    SWIFT · CONDITIONAL STATEMENTS

    Chaining Conditionals in Swift, explained

    More than two outcomes

    A single if with an else splits the program into two paths. When you need three, four or more outcomes, you chain extra tests with else if. Swift checks the conditions from top to bottom and runs the body of the first one that is true. Every later branch is skipped, and its condition isn't even evaluated.

    let language = "Python"
    if language == "JavaScript" {
        print("It's super popular!")
    } else if language == "Python" {
        print("It's so simple!")
    } else if language == "Java" {
        print("It's pretty hardcore!")
    } else {
        print("It's exotic!")
    }
    

    Here language == "JavaScript" is false, so Swift moves on. language == "Python" is true, so the program prints It's so simple! and leaves the chain. The final else has no condition. It catches everything the earlier tests did not match, so with "Go" the program would print It's exotic!.

    In Swift, the conditions need no parentheses, and the braces are always required, even for a one-line body.

    Order matters

    Because the first matching branch wins, the order of the tests decides the behaviour. When the tests are ranges of numbers, put them in order from the lowest limit to the highest. Each else if then only needs an upper bound, because every smaller value was handled by a branch above it.

    The exercise, step by step

    The lesson defines a grade constant and asks for four messages:

    GradeMessage
    below 5Failed the test
    5 to 7Passed the test
    8 to 9Good Job
    above 9Perfect
    1. Start with the failing grades. An if grade < 5 prints "Failed the test". Everything that reaches the next branch is therefore at least 5.
    2. Add the middle branches. else if grade <= 7 prints "Passed the test". It needs no lower bound, because grades below 5 never get here. Then else if grade <= 9 prints "Good Job". "Up to 7" and "up to 9" include those values, so the comparison is <=.
    3. Finish with else. Whatever is left is above 9, so a plain else prints "Perfect".
    let grade = 8
    
    if grade < 5 {
        print("Failed the test")
    } else if grade <= 7 {
        print("Passed the test")
    } else if grade <= 9 {
        print("Good Job")
    } else {
        print("Perfect")
    }
    

    With grade = 8, the first test is false (8 is not below 5), the second is false (8 is above 7), and the third is true, so the program prints Good Job. The last branch is never reached.

    Testing the boundaries

    Changing grade to each of these values gives the following output:

    gradeOutput
    3Failed the test
    5Passed the test
    7Passed the test
    8Good Job
    9Good Job
    10Perfect

    Values at the edges (4, 5, 7, 8 and 9) are the ones most likely to expose a wrong comparison.

    Common mistakes

    • Writing separate ifs. If the second and third tests start with if instead of else if, each test runs on its own. A grade of 4 would print Failed the test and then also Passed the test, because 4 is at most 7.
    • Putting the tests in the wrong order. If grade <= 9 came first, every grade up to 9 would print Good Job, and the later branches would never run.
    • Using < where <= is needed. With grade < 7, a grade of 7 would fall through to Good Job.
    • Writing a condition on else. A final else never takes one; if you need a test, use else if.

    Key takeaways

    • A chain runs at most one branch: the first whose condition is true.
    • List the tests in a deliberate order, and let later branches rely on what the earlier ones ruled out.
    • A closing else handles everything left over.
    • Test the values on both sides of each boundary.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free