案例和swift切换

时间:2015-02-05 09:07:45

标签: xcode swift

在下面显示的代码中,蔬菜多次声明为常量。但是Xcode没有出错。为什么Xcode成功编译它并没有得到和错误?让我们不变。?

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 sandwich."
​case​ ​let​ ​x​ ​where​ ​x​.​hasSuffix​(​"pepper"​):
​    ​let​ ​vegetableComment​ = ​"Is it a spicy ​\(​x​)​?"
​default​:
​    ​let​ ​vegetableComment​ = ​"Everything tastes good in soup."
​}

摘自:Apple Inc.“The Swift Programming Language。”iBooks

1 个答案:

答案 0 :(得分:3)

我认为你实际上是在谈论vegetableComment被定义为一个常数,这就是你所困惑的。

在Swift中,case:语句中的每个switch块都有自己的词法范围。 这意味着您可以在每个变量中将所有变量命名为相同,并且它们不会发生冲突。几乎就好像他们处于不同的职能部门一样。

同样,您无法访问其他变量。以下是一些例子:

let​ ​vegetable​ = ​"red pepper"
var comment = ""
​switch​ ​vegetable​ {
​case​ ​"celery"​:
​    ​comment​ = ​"Add some raisins and make ants on a log."
    // This is only defined here
    var favoriteVegetable = "celery"

​case​ ​"cucumber"​, ​"watercress"​:
​    ​comment​ = ​"That would make a good tea sandwich."
    // This will be an error, because `favoriteVegetable` is only valid inside the celery case block
    // favoriteVegetable = "either cucumber or watercress"

​case​ ​let​ ​x​ ​where​ ​x​.​hasSuffix​(​"pepper"​):
​    ​comment​ = ​"Is it a spicy ​\(​x​)​?"

    // We can redefine favoriteVegetable here, because it has nothing to do with the one in the celery block
    let favoriteVegetable = "a pepper"

​default​:
​    ​comment​ = ​"Everything tastes good in soup."
​}

// Similarly, we can't access `favoriteVegetable` here
// println(favoriteVegetable)

// This was defined before the switch statement, so we can get the value that was calculated
println(comment)