Learn
Conditionals
Switch Statement: Interval Matching

One super power that the switch statement possesses, is its ability to match values to an expression that exist within intervals. An interval denotes a range used for checking whether a given value lies within that range.

In Swift, a range is indicated by three consecutive dots, ..., also known as the closed range operator. The closed range operator signifies an inclusive range where the first and last values are included in the sequence.

Let’s see these new concepts in action. In the example below, the switch statement determines the value of year and checks which century it belongs to.

var year = 1943 switch year { case 1701...1800: print("18th century") case 1801...1900: print("19th century") case 1901...2000: print("20th century") case 2001...2100: print("21st century") default: print("You're a time traveler!") } // Prints: 20th century

Since the year, 1943, falls between the interval, 1901...2000, the code for the third case is executed and the message, 20th century gets printed.

Fun fact: The first electronic computer was built in 1943! πŸ’»

Instructions

1.

In StarWarsVillains.swift, we’ll create a switch statement that determines the villain in a Stars Wars episode. We’ve declared and initialized two variables that will be used throughout our switch statement.

First, create a switch statement that accepts episode 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.

Within the {} of your switch statement, create case intervals using the following information:

  • Episode 1 through 3: villain is "Emperor Palpatine"
  • Episode 4 through 6: villain is "Darth Vader"
  • Episode 7 through 9: villain is "Kylo Ren"

Add a default statement that assigns an empty string, "" to villain.

3.

After the switch statement, print villain.

4.

Continue practicing in the editor by testing your code with different values for episode or adding more cases to the switch statement. Make sure it’s working as expected before moving on.

Folder Icon

Take this course for free

Already have an account?