Assign value to optional dictionary in Swift

dictionary, swift

Solution

The lightbulb moment is when you realize that an Optional dictionary is not a Dictionary. An Optional anything is not that thing! It is an Optional!! And that's all it is. Optional is itself a type. An Optional is just an enum, wrapping the possible cases nil and some value. The wrapped value is a completely different object, stored inside.

So an Optional anything does not act like the type of that thing. It is not that thing! It is just an Optional. The only way to get at the thing is to unwrap it.

The same is true of an implicitly unwrapped Optional; the difference is just that the implicitly unwrapped Optional is willing to produce (expose) the wrapped value "automatically". But it is still, in fact, wrapped. And, as Bryan Chen has observed, it is wrapped immutably; the Optional is just holding it for you - it is not giving you a place to play with it.

Problem

I'm finding some surprising behavior with optional dictionaries in Swift. ``` var foo:Dictionary<String, String>? if (foo == nil) { foo = ["bar": "baz"] } else { // Following line errors with "'Dictionary<String, String>?' does // not have a member named 'subscript'" foo["qux"] = "quux" } ``` I've played with this a lot, trying to figure out what I might be missing, but nothing seems to make this code work as expected short of making the dictionary not optional. What am I missing? The closest I can get is the following, but of course it's ridiculous. ``` var foo:Dictionary<String, String>? if (foo == nil) { foo = ["bar": "baz"] } else if var foofoo = foo { foofoo["qux"] = "quux" foo = foofoo } ```

Original source