ios - 在 Swift 中使用可选值

标签 ios cocoa swift

在阅读 The Swift Programming Language 时,我遇到了这个片段:

You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that the value is missing. Write a question mark (?) after the type of a value to mark the value as optional.

// Snippet #1
var optionalString: String? = "Hello"
optionalString == nil

// Snippet #2     
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello, \(name)"
}

片段 #1 已经足够清楚了,但是片段 #2 中发生了什么?有人可以分解并解释吗?它只是使用 if - else block 的替代方法吗? let 在这种情况下的确切作用是什么?

我读过 this页面,但还是有点困惑。

最佳答案

if let name = optionalName {
   greeting = "Hello, \(name)"
}

这做了两件事:

  1. 它检查 optionalName 是否有值

  2. 如果是,它会“展开”该值并将其分配给名为 name 的字符串(仅在条件 block 内可用)。

请注意,name 的类型是String(不是String?)。

如果没有 let(即只有 if optionalName),只有在有值时它仍然会进入 block ,但你必须手动/显式地以 optionalName! 的形式访问字符串。

关于ios - 在 Swift 中使用可选值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24030053/

相关文章:

ios - 当您有多个应用程序支持相同的外部附件协议(protocol)时会发生什么?

objective-c - cocoa 将 CIImage 保存为 bmp 文件图像损坏

cocoa 沙盒: How to get permission to write multiple files or to a directory with NSSavePanel

swift - 重叠访问 'urlComponents' ,但修改需要独占访问

ios - iOS 下载文件时的进度条

ios - Swift 3 NSMutableURLRequest 第二次调用失败

macos - NSMenu 初始值设定项或 didLoad 等效项?

ios - Swift 可失败初始化器不能返回 Nil?

ios - 用户默认值仅在重启时工作

ios - 如何使用 RestKit Testing 测试此对象映射