gpt4 book ai didi

xcode - Swift:来自 switch 语句的未解析标识符

转载 作者:搜寻专家 更新时间:2023-11-01 05:59:31 24 4
gpt4 key购买 nike

我正在 Xcode6-Beta4 的 Playground 上尝试以下操作,跟随苹果的 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 语句的作用域/闭包有关?

最佳答案

Is it something relating the the scope / closure of switch statement in swift?

是的,跟变量的作用域有关。您有四个名为 vegetableComment 的常量。每一个都限定在 switch 语句的 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."
}

关于xcode - Swift:来自 switch 语句的未解析标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25264050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com