Swift - setting dictionary value to nil confusion
/// If you assign `nil` as the value for the given key, the dictionary
/// removes that key and its associated value.
This is a sentence from the documentation, so as you can see it is by design. If this not fit your needs then you are doomed to use updateValue(value: Value, forKey: Hashable)
which also works more predictable.
What I found is that when you use NSMutableDictionary
instead of Dictionary
then it works as "expected"
let ns = NSMutableDictionary(dictionary: d)
let x: Any? = nil
ns["foo"] = x // ns {}
However let x = Any? = nil
case seems that there is a bug in Swift implementation at least to version Apple Swift version 3.0.1 (swiftlang-800.0.58.6 clang-800.0.42.1)
Btw. when all elements from Dictionary
are removed, type
of Dictionary
is still correctly recognised
let x: String? = nil
d["foo"] = x // d is now [:]
let m = Mirror(reflecting: d) // Mirror for Dictionary<String, Optional<Any>>
I allowed myself to add bug to Swift lang: https://bugs.swift.org/browse/SR-3286
Given a dictionary like this:
dict: [String: String?] = []
If you add nil
value like this:
dict["a"] = nil
The dictionary will be empty. However, if you add a nil
value like this:
dict["a"] = nil as String?
The dictionary will not be empty. Try it out...
func testDictionary() {
var dict: [String: String?] = [:]
dict["abc"] = nil
print("dictionary is empty -> \(dict.isEmpty)") // -> true
dict["abc"] = nil as String?
print("dictionary is empty -> \(dict.isEmpty)") // -> false
}
This seems very odd behavior and a subtle difference. Can someone explain?