我在Xcode6-Beta4的操场上尝试以下操作,跟随苹果swift tour:
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."
}
然后我尝试调用switch语句中定义的变量vegetableComment
,我得到Use of unresolved identifier 'vegetableComment'
错误
是否与swift中switch语句的范围/闭包有关?
答案 0 :(得分:6)
是否与swift中switch语句的范围/闭包有关?
是的,它与变量的范围有关。你有四个常量叫vegetableComment
。每个范围都限定在case
语句的switch
。
要访问您在switch
内分配的变量,您需要在进入交换机之前将其声明为var
:
var vegetableComment = String()
let vegetable = "red pepper"
switch vegetable{
case "celery":
vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
vegetableComment = "Is it a spicy \(x)"
default:
vegetableComment = "Everything tastes good in soup."
}