[swift-users] Dictionary with optional values
swift-users_me at mayerscraft.com
Wed May 18 13:03:40 CDT 2016
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?
> On 18 May 2016, at 18: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.
> swift-users mailing list
> swift-users at swift.org
More information about the swift-users