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

时间:2014-06-02 22:23:43

标签: 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."
}
  

控制台输出

     

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

似乎正在发生以下逻辑。

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

有人可以为我更好地解释这个吗?

2 个答案:

答案 0 :(得分:21)

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

var vegetable: String = "red pepper"

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

您可以详细了解whereswitch here

答案 1 :(得分:0)

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

在switch语句的情况下使用let在其他情况下很有用,例如,当“参数”(蔬菜)不是变量时,例如switch(getVegetableName()),或者在“参数”是元组并且需要解压的情况下,例如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")
}