Start learning free

LESSON 80 OF 349 · CONDITIONAL STATEMENTS

Chaining Conditionals in Swift in Swift

Lesson

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 3
    Ctrl + Enter to check

    Chaining Conditionals in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free