Swift常量赋值示例

时间:2018-03-26 16:46:27

标签: ios swift constants

我是一位长期开发人员(java,c,c ++等)和一位有问题的Swift新手。在下面的switch语句中,常量" x"定义示例状态"注意如何在模式中使用let将模式匹配的值分配给常量。" 。我有点困惑,因为该语句没有引用switch语句的目标变量" vegetable"一点都不我的想法应该是:

case let x where vegetable.hasSuffix("pepper"):
        -- or just --
case let x where hasSuffix("pepper"):

而不是

    case let x where x.hasSuffix("pepper"):

我们将不胜感激。

Swift Tutorial

let vegetable = "red pepper"
switch vegetable {
case "celery":
    print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
    print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
    print("Is it a spicy \(x)?")
default:
    print("Everything tastes good in soup.")
}

2 个答案:

答案 0 :(得分:2)

where谓词可以直接引用vegetable这个特殊情况,它编译得很好。

switch vegetable {
case "celery":
    print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
    print("That would make a good tea sandwich.")
case let x where vegetable.hasSuffix("pepper"):
    print("Is it a spicy \(x)?")
default:
    print("Everything tastes good in soup.")
}

但现在考虑更复杂的vegetable模式匹配,假设它是String?(a.k.a。Optional<String>)而不是String

let vegetable: String? = "red pepper"
switch vegetable {
case "celery"?:
    print("Add some raisins and make ants on a log.")
case "cucumber"?, "watercress"?:
    print("That would make a good tea sandwich.")
case let x? where vegetable.hasSuffix("pepper"):
    //            ^ error: value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?
    print("Is it a spicy \(x)?")
case nil:
    print("You don't even have a vegetable!")
default:
    print("Everything tastes good in soup.")
}

在这种情况下,x在非零情况下是vegetable的非可选值,允许用来在其上调用.hasSuffix("pepper")。它说&#34;如果菜是有价值的情况,请将其称为x,恰好以"pepper"结束,然后执行以下操作:...&#34 ;

答案 1 :(得分:0)

与@Alexander聊天后,我对交换机构造有了更好的理解。感谢他的时间和解释。

如本Control Constructs文档的“值绑定”部分所述,我了解到switch语句在评估案例之前将临时变量分配给switch目标的值。因此,右侧(临时x)被分配了开关目标值“红辣椒”,并且每个开关盒从上到下匹配的情况模式。如果情况匹配则左侧x成为永久常数。净网,临时x被定义并且set = vegetable然后执行开关模式匹配。

 case let x where x.hasSuffix("pepper"):