[swift-users] Dictionary with optional values

Jens Alfke jens at mooseyard.com
Wed May 18 13:16:04 CDT 2016

> On May 18, 2016, at 11:03 AM, Artyom Goncharov via swift-users <swift-users at swift.org> wrote:
> Yes, of course I can use API method but this kind of behaviour for subscript operator seems inconsistent(or even magical) to me because it is possible to initialise a dictionary with nil without casting it. Though nil is a special case it is still a value in the set of all values of a T? type, am I wrong?

It’s an unfortunate ambiguity, one that comes up in any dictionary API that potentially allows nil to be stored as a value. Does a RHS of nil mean to remove the key/value pair, or to store a nil as the value?

In particular, the C++ STL goes through horrible contortions to get around this, which is part of what makes it so awful and verbose to use. :-P

The intuitive (and most commonly useful) interpretation of “dict[x] = nil” is to remove the key, which is what Swift does. If you’ve created a dictionary of optionals and need to store a null, you have to add a bit of verbosity to make your intention clear. I think that’s fine: it goes along with Alan Kay’s maxim that “simple things should be simple, and complex things should be doable.”

(Thinking about it, I can’t see much use for a dictionary of optionals. What’s the difference between “x has no value” and “x has a value of nil”? I guess it’s that when you iterate the keys you see x. This seems like a tricky use that could easily confuse someone reading the code (who could be you, a year later!) Personally I’d prefer a different, clearer solution, unless this was something performance-critical that led to faster code. In which case I’d add lots of comments!)


More information about the swift-users mailing list