Swift "where" key word
Swift's switch
statements are much more powerful than the ones used in most other languages. Instead of simply choosing from a group of values, they use pattern-matching to select which case
to evaluate. Let's look at each case
from your example:
case "celery":
Super simple -- this will match the string "celery"
and nothing else.
case "cucumber", "watercress":
This case will match either the string "cucumber"
or the string "watercress"
. Cool. In other languages you'd probably need to use a fallthrough case to get both of these.
case let x where x.hasSuffix("pepper"):
This case contains two concepts that are particular to Swift switch
statements, when compared to Java and C. The first is value-binding -- the let x
part of this statement binds the matched value to a constant x
that is scoped to the case's body.
Next is the where
clause. This is a boolean test, just like an if
statement, so the case only matches if the expression is true
. In this example, x.hasSuffix("pepper")
looks at the bound value and checks to see if it ends with "pepper"
. The strings "red pepper"
, "green pepper"
, and "spicy hot pepper"
would all match, but "peppercorns"
would not.
default:
In Swift, switch
statements need to exhaust all the possible values of the matched value, so they typically end with a default:
case block to handle any value that wasn't previously matched. The only time you wouldn't see this is if you're matching an enum
with only a few values, since you could manually exhaust all the options.
You can include multiple optional bindings in a single if statement and use a where clause to check for a Boolean condition:
if let firstNumber = Int("4"), secondNumber = Int("42") where firstNumber < secondNumber { print("\(firstNumber) < \(secondNumber)")}// prints "4 < 42