如何让x在x.hasSuffix("pepper")中起作用

Ari*_*osh 9 swift swift-playground

在下面的代码块中,我无法理解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."
}
Run Code Online (Sandbox Code Playgroud)

控制台输出

vegetableComment:这是一种辛辣的红辣椒

似乎发生了以下逻辑.

x = vegetable
if (x's suffix == 'pepper') 
    run case
Run Code Online (Sandbox Code Playgroud)

有人能帮我解释一下吗?

Lea*_*ros 21

vegetable是隐含的String.它和你写的一样:

var vegetable: String = "red pepper"
Run Code Online (Sandbox Code Playgroud)

hasSuffix声明为func hasSuffix(suffix: String) -> Bool因此返回a Bool.该where关键字指定额外的要求,并且只能在使用switch的语句.
因为所有这些都是vegetable泛型的,所以变量被赋值给x(let x).

你可以阅读更多有关whereswitch 在这里.