Another noteworthy ability of the switch
statement is its use of multiple values in a single case. These are known as compound cases. The switch
statement will match each value within a compound case to the given expression.
The following code checks the value of country
and determines the continent on which it is located using a switch
statement. Since a continent may consist of multiple countries, compound cases deem useful:
var country = "India" switch country { case "USA", "Mexico", "Canada": print("\(country) is in North America. π") case "South Africa", "Nigeria", "Kenya": print("\(country) is in Africa. π") case "Bangladesh", "China", "India": print("\(country) is in Asia. π") default: print("This country is somewhere in the world!") } // Prints: India is in Asia. π
Notice howβ¦
- The multiple values or items in a compound case are separated by a comma.
- We used string interpolation to output the value of
country
within theString
of theprint()
statement.
Instructions
The 8 planets within our solar system are often categorized as terrestrial or jovian planets. In Planets.swift, weβll set up a switch
statement that utilizes compound cases to determine the type of planet its given.
First, create a switch
statement that accepts planet
as its expression. Keep the body of the switch
statement empty for now.
Note: You will see an error in the terminal on the right, but it will go away in the next step when we add case
statements!
Use the following information to set up the case
statements within the switch
:
"Earth"
,"Mercury"
,"Venus"
, and"Mars"
fall under the"Terrestrial planet"
category."Saturn"
,"Jupiter"
,"Uranus"
, and"Neptune"
fall under the"Jovian planet"
category.Each
case
should contain aprint()
statement that outputs the planetβs category.
Lastly, use a default
statement that outputs Unknown planet
.
Continue practicing in the editor by testing your code with different values for planet
. Make sure itβs working as expected before moving on.