在下面显示的代码中,蔬菜多次声明为常量。但是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."
}摘自:苹果公司。“Swift编程语言。”iBooks。
发布于 2015-02-05 17:26:45
我假设您实际上是在谈论将vegetableComment定义为常量,这就是您所困惑的。
在Swift中,switch语句中的每个case:块都有自己的词法作用域。这意味着您可以在每个变量中为所有变量指定相同的名称,并且它们不会冲突。几乎就像它们在不同的功能中一样。
同样,您不能访问其他变量。下面是一些示例:
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)https://stackoverflow.com/questions/28339943
复制相似问题