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