In the code block below, I am having trouble understanding let x where x.hasSuffix("pepper").
let vegetable = "red pepper"
switch vegetable {
case "celery":
let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
let vegetableComment = "That would make a good tea sandwhich"
case let x where x.hasSuffix("pepper"):
let vegetableComment = "Is it a spicy \(x)"
default:
let vegetableComment = "Everything tastes good in soup."
}
Console output
vegetableComment: Is it a spicy red pepper
It seems like the following logic is happening.
x = vegetable
if (x's suffix == 'pepper')
run case
Can someone explain this better for me?
vegetable is an implicit String. It's the same as you would write:
var vegetable: String = "red pepper"
hasSuffix is declared as func hasSuffix(suffix: String) -> Bool an therefore returns a Bool. The where keyword specifies additional requirements, and can only be used in switch statements.
Because all of this is suffused, the vegetable variable is assigned to x (let x).
You can read more about the where and switch here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With