gpt4 book ai didi

ios - 在 if 语句中声明变量时使用未解析的标识符

转载 作者:可可西里 更新时间:2023-11-01 00:38:25 26 4
gpt4 key购买 nike

为什么在 then 子句中 name 被解析为变量,但在 else 子句中我得到错误:

使用未解析的标识符 'name'

代码:

    var optionalName: String? = "Peter"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
else {
greeting = "Hello, \(name)"
}

最佳答案

因为这就是可选绑定(bind)的工作方式。

仅当 optionalName 不为空时,

name 才会被初始化和分配。

如果 optionalNamenil,您进入 else 分支并且您已经知道 optionalName 是空。

来自官方书:

If the optional value is nil, the conditional is false and the code in braces is skipped. Otherwise, the optional value is unwrapped and assigned to the constant after let, which makes the unwrapped value available inside the block of code.

关于ios - 在 if 语句中声明变量时使用未解析的标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24035439/

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