[swift-users] Dictionary with optional values

Jordan Rose jordan_rose at apple.com
Wed May 18 19:26:49 CDT 2016


> On May 18, 2016, at 09:38, Ray Fix via swift-users <swift-users at swift.org> wrote:
> 
> 
>> 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.

There’s a bit more discussion of this on the Apple Swift blog: https://developer.apple.com/swift/blog/?id=12 <https://developer.apple.com/swift/blog/?id=12>

Jordan

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160518/b6a05d34/attachment.html>


More information about the swift-users mailing list