swift - 字典中可选值的意外 nil 检查结果

标签 swift cocoa

我注意到在检查字典中的值是否为 nil 时,我发现了一种令人困惑的行为。在某个通知的通知处理程序中,我想检查错误键的值是否为零。在尝试调试时,我尝试了以下操作:

po userInfo["error"]

▿ Optional - some : nil

(lldb) po userInfo["error"] == nil

false

鉴于第一个命令的输出,我希望第二个命令返回 true。有什么想法吗?

谢谢

最佳答案

userInfo["error"]正在回馈Optional<Sometype>.some(Optional<SomeOtherType>.none) .所以 userInfo字典确实 有关键字"error" 的值,但该值是另一个 Optional,它本身是 nil .

这是模仿结构的代码片段:

let userInfo: [String: String?] = [
    "something": "something else",
    "another thing": "yet another thing",
    "error": nil
]

print(userInfo["error"] as Any) // Optional(nil)

关于swift - 字典中可选值的意外 nil 检查结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46758196/

相关文章:

objective-c - 使用 extern 指令导入 const double 构建失败

ios - 使用 Rest API Swift 3

ScrollView 下的 SwiftUI 点击

ios - 为什么不调用 deinit?

ios - 延迟显示异步获取的项目

iphone - 获取 nsstring 的实例 ID

objective-c - NSButton 的弹出菜单实现

cocoa - 如何将 NSMutableData 转换为 View 中的图像?

arrays - 二维数组 : Index out of range

ios - 如何判断当前线程是否创建为 NSThread?