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 eachcase
within theswitch
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 thatcase
is executed and theswitch
completes its checking.Very much similar to an
else
statement, if a matching value isnβt found, thedefault
statement gets evaluated.
Instructions
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.
Following the switch
statement, print superheroName
.