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

标签 swift dictionary unwrap

给定下面的字典,解包 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...

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

最佳答案

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

let dbOpt = dict[x]?[y]

我最喜欢的:

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

使用flatMap:

if let goo = dbOpt.flatMap{$0} { foo = goo } 

使用模式匹配:

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

关于swift - 如何一步解开 Swift 4+ 中的可选字典值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53440636/

相关文章:

loops - Ansible 从列表中创建目录

java - 如何在 REST 服务中获取不同 mime 类型的 Map 参数?

python - 询问字典中两个值中的一个

swift - 为什么在 swift 中变量选项是在函数中而不是在 Playground 中

ios - 如何在小游戏中正确复用UIView?

ios - UIImage 不会显示带有白色前景图案的 PNG

swift - 可选的多重解包

performance - 为什么选择 `unwrap_or_else` 而不是 `unwrap_or` ?

ios - 我无法让我的 MKRoute 显示在 MapView 上

ios - 准备segue时的Segue特定值