In the code block below, I am having trouble understanding let x where x.hasSuffix(\"pepper\")
.
let vegetable = \"red pepper\"
switch vegetable {
There is actually no reason to use let x
in this scenario. case let x where x.hasSuffix("pepper"):
can simply be replaced with case vegetable where vegetable.hasSuffix("pepper")
. In this scenario, an extra variable x
is declared which copies vegetable
. This is useless, and arguable reduces readability, even if you renamed x
to vegetable
as well.
Using let
in a switch statement case is useful in other cases, such as when the "argument" (vegetable) is not a variable, e.g. switch(getVegetableName())
, or in the case where the "argument" is a tuple, and needs to be unpacked, such as in
let vegetableNameAndCountry = ("Sweet Potato", "United States")
switch(vegetableNameAndCountry) {
case (let vegetable, let country) where country == "Tanzania":
print("This \(vegetable) comes from a country north of Kenya")
case ("Sweet Potato", _): // Note here I ignore the country, and don't even bother creating a constant for it
print("Sweet sweet potatoes")
default:
print("We don't care about this vegetable")
}