[swift-users] Dictionary with optional values

Marco S Hyman marc at snafu.org
Wed May 18 13:16:40 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?

There are a few ways to assign nil to a dictionary entry.  First of all

dictionary[“key”] = nil

always removes “key" from dictionary.  To assign a nil value use one of:

dictionary[“key”] = Optional(nil)
dictionary[“key”] = .Some(nil)
dictionary[“key”]? = nil

That last only works if “key” already exists in the dictionary, i.e. you are replacing the existing value.  The first two will add a dictionary entry if necessary.

I suspect now that you’ve been bitten by this you will remember it forever :)


More information about the swift-users mailing list