如何一步解包 Swift 4+ 中的可选字典值?

How to unwrap an optional dictionary value in Swift 4+ in one step?

给定下面的字典,解包 Int 的正确语法是什么?一步到位?

let dict:Dictionary<String, Dictionary<String, Int?>> = [
"parentKey" : [
    "firstKey" : 1,
    "secondKey" : nil]
]

let x = "someKey"
let y = "someOtherKey"
var foo = 0

if let goo = dict[x]?[y] { foo = goo } //<-- Error: cannot assign (Int?) to Int

if let goo = dict[x]?[y], let boo = goo { foo = boo } //<-- OK

在第一个'if let'中,goo作为Int返回? - 然后需要像第二个 'if let'...

一样解开 goo

一步完成此操作的正确语法是什么?

使用 nil 合并并提供默认值。安全解包字典值的唯一方法。

if let goo = dict[x]?[y] ?? NSNotFound { foo = goo }  

据我了解,您想强制解包一个双可选。有不同的方法。

let dbOpt = dict[x]?[y]

我最喜欢的:

if let goo = dbOpt ?? nil { foo = goo } 

使用flatMap

if let goo = dbOpt.flatMap{[=12=]} { foo = goo } 

使用模式匹配:

if case let goo?? = dbOpt { foo = goo }

有很多方法可以做到这一点,但最简单的解决方案之一是:

var foo = 0

if let goo = dict[x]?[y]  as? Int{
    foo = goo
}
print(foo)