首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >case and switch in swift

case and switch in swift
EN

Stack Overflow用户
提问于 2015-02-05 17:07:45
回答 1查看 1.6K关注 0票数 0

在下面显示的代码中,蔬菜多次声明为常量。但是Xcode没有收到错误。为什么Xcode成功地编译了它,但没有得到和错误?设是一个常数。?

代码语言:javascript
复制
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."
​}

摘自:苹果公司。“Swift编程语言。”iBooks

EN

回答 1

Stack Overflow用户

发布于 2015-02-05 17:26:45

我假设您实际上是在谈论将vegetableComment定义为常量,这就是您所困惑的。

在Swift中,switch语句中的每个case:块都有自己的词法作用域。这意味着您可以在每个变量中为所有变量指定相同的名称,并且它们不会冲突。几乎就像它们在不同的功能中一样。

同样,您不能访问其他变量。下面是一些示例:

代码语言:javascript
复制
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)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28339943

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档