Learn

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 the String of the print() statement.

Instructions

1.

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!

2.

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 a print() statement that outputs the planet’s category.

Lastly, use a default statement that outputs Unknown planet.

3.

Continue practicing in the editor by testing your code with different values for planet. Make sure it’s working as expected before moving on.

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?