Assign value to optional dictionary in Swift

后端 未结 4 1177
北恋
北恋 2020-12-10 04:42

I\'m finding some surprising behavior with optional dictionaries in Swift.

var foo:Dictionary?

if (foo == nil) {
    foo = [\"bar\": \         


        
4条回答
  •  -上瘾入骨i
    2020-12-10 05:26

    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.

提交回复
热议问题