9

在下面的代码块中,我无法理解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."
}

控制台输出

蔬菜评论:是不是辣的红辣椒

似乎正在发生以下逻辑。

x = vegetable
if (x's suffix == 'pepper') 
    run case

有人可以为我更好地解释一下吗?

4

2 回答 2

21

vegetable是隐含的String。这和你写的一样:

var vegetable: String = "red pepper"

hasSuffix被声明为func hasSuffix(suffix: String) -> Boolan 因此返回 a Bool。关键字指定附加要求,where并且只能在switch语句中使用。
因为所有这些都被泛滥了,所以vegetable变量被分配给 x ( let x)。

您可以在此处阅读有关where和的更多信息。switch

于 2014-06-02T23:09:40.910 回答
0

实际上没有理由let x在这种情况下使用。case let x where x.hasSuffix("pepper"):可以简单地替换为case vegetable where vegetable.hasSuffix("pepper"). 在这种情况下,声明了一个额外的变量x来复制vegetable. 这是无用的,并且有争议会降低可读性,即使您也重命名xvegetable

在 switch 语句中使用letcase 在其他情况下很有用,例如当“参数”(蔬菜)不是变量时,例如switch(getVegetableName()),或者在“参数”是元组并且需要解包的情况下,例如在

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")
}
于 2020-10-07T15:19:38.667 回答