Given the dictionary of dictionary below, what is the correct syntax to unwrap the Int? in one step?
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
In the first 'if let', goo is returned as an Int? - goo then needs to be unwrapped as in the second 'if let'...
What is the correct syntax for doing this in one step?
As far as I understood you want to force unwrap a double optional. There different methods.
My favorite:
Using
flatMap
:Using pattern matching: