Dictionary<AnyHashable: Any> where Any may hold nil value in Swift 3

Rafael Sacchi picture Rafael Sacchi · Dec 12, 2016 · Viewed 11.4k times · Source

Can someone explain why this works in Swift 3?

var dict: [AnyHashable: Any]
let b: AnyObject? = nil
let c = b as Any

dict = ["a": "aa", "b": c]

If I test

dict["b"] == nil

It returns false. Is it supposed to be right?

Answer

bobDevil picture bobDevil · Dec 12, 2016

You're running into nested optionals. If a dictionary holds a type E, then the dictionary access method returns a value of type E?, either the value if it exists, or nil.

In your case, you've created a dictionary where the value is an optional. So the E above is something like Any?. This means the return value of the getter is E? i.e., Any??

In your case, dict["b"] returns a non-nil optional, containing the value 'nil'

Putting your code in a playground and printing dict["b"] confirms this by printing the string Optional(nil)