Learn

Another type of conditional statement that exists in Swift is the switch statement. The switch statement is a popular programming tool used to check the value of a given expression against multiple cases. The switch statement is a lot more powerful in Swift than it is in other programming languages, thus we’ll be dedicating the next few exercises to explore its features.

Unlike the if statement, a switch statement does not check for the value of a condition and instead finds and matches a case to a given expression.

Let’s take a look at an example where a switch statement can be used. The code below uses multiple else if statements within an if/else to match a landmark to a given city:

var city = "Rome" if city == "Rapa Nui" { print("Moai πŸ—Ώ") } else if city == "New York" { print("Statue of Liberty πŸ—½") } else if city == "Rome" { print("Colosseum πŸ›") } else { print("A famous landmark is the Eiffel Tower!") }

Since this code involves a series of else if comparisons, it’s the perfect candidate for a switch statement rewrite:

switch city { case "Rapa Nui": print("Moai πŸ—Ώ") case "New York": print("Statue of Liberty πŸ—½") case "Rome": print("Colosseum πŸ›") default: print("A famous landmark is the Eiffel Tower!") }

Notice how…

  • Our new conditional begins with the switch keyword and is followed by the variable, city which acts as the expression. The value of the expression, originally "Rome", is checked against each case within the switch block.

  • The corresponding code to execute for a case is followed by a colon, :.

  • Once the value has been matched with a case, the code for that case is executed and the switch completes its checking.

  • Very much similar to an else statement, if a matching value isn’t found, the default statement gets evaluated.

Instructions

1.

In Superheroes.swift, we have a series of else if statements that match a superhero’s secret identity to their superhero name.

Rewrite this conditional in switch statement format.

2.

Following the switch statement, print superheroName.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?