Advanced switch statements
You can also give your switch statements more than one case. In the previous chapter, you saw an if statement using multiple else-if statements to convert an hour of the day to a string describing that part of the day. You could rewrite that more succinctly with a switch statement, like so:
let hourOfDay = 12 let timeOfDay: String
switch hourOfDay { case 0, 1, 2, 3, 4, 5:
timeOfDay = "Early morning" case 6, 7, 8, 9, 10, 11:
timeOfDay = "Morning"
case 12, 13, 14, 15, 16:
timeOfDay = "Afternoon" case 17, 18, 19:
timeOfDay = "Evening" case 20, 21, 22, 23:
timeOfDay = "Late evening" default:
timeOfDay = "INVALID HOUR!"
}
print(timeOfDay)
This code will print the following:
Afternoon
Remember ranges? Well, you can use ranges to simplify this switch statement. You can rewrite it using ranges as shown below:
let hourOfDay = 12 let timeOfDay: String
switch hourOfDay { case 0...5:
timeOfDay = "Early morning" case 6...11:
timeOfDay = "Morning" case 12...16:
timeOfDay = "Afternoon" case 17...19:
timeOfDay = "Evening" case 20..<24:
timeOfDay = "Late evening" default:
timeOfDay = "INVALID HOUR!"
}
This is more succinct than writing out each value individually for all cases.
When there are multiple cases, the statement will execute the first one that matches. You’ll probably agree that this is more succinct and more clear than using an if statement for this example. It’s slightly more precise as well, because the if statement method didn’t address negative numbers, which here are correctly deemed to be invalid.
It’s also possible to match a case to a condition based on a property of the value. As you learned in Chapter 2, you can use the modulo operator to determine if an integer is even or odd. Consider this code:
let number = 10
switch number {
case let x where x % 2 == 0: print("Even")
default: print("Odd")
}
This will print the following:
Even
This switch statement uses the let-where syntax, meaning the case will match only when a certain condition is true. The let part binds a value to a name, while the where part provides a Boolean condition that must be true for the case to match. In this example, you’ve designed the case to match if the value is even — that is, if the value modulo 2 equals 0.
The method by which you can match values based on conditions is known as
pattern matching.
In the previous example, the binding introduced a unnecessary constant x; it’s simply another name for number. You are allowed to use number in the where clause and replace the binding with an underscore to ignore it:
let number = 10
switch number {
case _ where number % 2 == 0: print("Even")
default: print("Odd")
}