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

标签 ios if-statement swift

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

使用未解析的标识符“名称”

代码:

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

最佳答案

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

name 仅当 optionalName 不为空时才会被初始化和分配。

如果 opticalNamenil,您将进入 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 after let, which makes the unwrapped value available inside the block of code.

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

相关文章:

ios - 应用程序转到后台后,AVAudioPlayer 停止返回正确的当前时间

iOS 10 Firebase 通知未在后台显示

ios - MultiPeer MCNearbyBrowserService 崩溃

arrays - 如何检查给定单元格是否包含任何数字?

ios - UIImageView 适合自适应表格 View 单元格中的最大宽度

ios - iOS 6 MapKit 是否适用于早期版本的 iOS?

Excel 2010 在 IF 函数中搜索文本 - 单独的单元格数据

java - while & for 循环和 JOptionPane 数据输入连接到 for 循环

swift - 如何用字符替换特定范围的字符串?

iOS 8 : Background execution