[swift-users] Dictionary with optional values

Ray Fix rayfix at gmail.com
Wed May 18 11:38:57 CDT 2016

> On May 18, 2016, at 3:56 AM, Artyom Goncharov via swift-users <swift-users at swift.org> wrote:
> var noOptDict = ["one": 1, "two": 2, "three": 3 ]
> noOptDict["one"] = nil

Wow, interesting.  To me this was surprising behavior too.

The comment for Dictionary subscript  says:

    /// Access the value associated with the given key.
    /// Reading a key that is not present in `self` yields `nil`.
    /// Writing `nil` as the value for a given key erases that key from
    /// `self`.

Which is exactly what it is doing.  As the Zhaoxin said, you can use updateValue (and removeValueForKey) to get better results when dealing with optional dictionary values.


More information about the swift-users mailing list