为什么在 then
子句 name
被解析为变量,但在 else
子句中我收到错误:
使用未解析的标识符“名称”
代码:
var optionalName: String? = "Peter"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
else {
greeting = "Hello, \(name)"
}
最佳答案
因为这就是可选绑定(bind)的工作原理。
name
仅当 optionalName
不为空时才会被初始化和分配。
如果 opticalName
为 nil
,您将进入 else
分支,并且您已经知道 opticalName
是空。
摘自官方书籍:
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 afterlet
, which makes the unwrapped value available inside the block of code.
关于ios - 在 if 语句中声明变量时使用未解析的标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24035439/