在阅读 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)"
}
这做了两件事:
它检查
optionalName
是否有值如果是,它会“展开”该值并将其分配给名为
name
的字符串(仅在条件 block 内可用)。
请注意,name
的类型是String
(不是String?
)。
如果没有 let
(即只有 if optionalName
),只有在有值时它仍然会进入 block ,但你必须手动/显式地以 optionalName!
的形式访问字符串。
关于ios - 在 Swift 中使用可选值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24030053/