I found that the design of Dictionary type in Swift is ambiguous.
Let start the discussion via an example first.
Example:
var d: [String : Int?] = ["aa": 123, "cc": 456, "bb": nil] // values are of type optional Int
d.count // 3, it is correct ???, I am not sure it is correct or not, but according to design, "bb": nil is an item so that it is correct.
d["cc"] = nil // this item with key "cc" is removed out of d WHY this item is removed? d[ ] should just do update or add new item instead of remove
print(d) // ["aa": Optional(123),"bb": nil]
d["bb"] = nil // this item with key "bb" is removed WHY this item is removed???
print(d) // ["aa": Optional(123)]
d["ee"] = nil // try to add an item with value nil into d BUT not add the new item into this dictionary. WHY???
print(d) // ["aa": Optional(123)]
I think the design of Dictionary type in Swift has some space to improve.
Because that Swift adds optional value into Dictionary so that Swift's designers need to think more careful about nil
When we accept "bb": nil as an valid item in Dictionary we should allow to add a new item with value of nil into dictionary.
When we change "cc": 456 to "cc": nil, it should just change the value to nil, instead of removing the item out of the dictionary.
By the way, in the current design of Dictionary, We use the
removeValue(forKey:)
methodto remove a key-value pair from a dictionary .I think the method name "removeValue(forKey:) is not a proper name, it is better to change it to removeKey() because that key is the keypoint of an item in Dictionary and the type of key is a nonoptional type. (Swift does not allow [String? : Int] )
By the way I also check Array in Swift, it seems OK no problem to work with optional value.
it allows [Int?], for example, [1, nil, 3, nil, nil, 6] (its count is 6), see example below
var a:[Int?] = [1,2,nil,4,5]
print(a.count)
a[1] = nil
print(a)
print(a.count)
a.append(nil)
print(a)
print(a.count)
Output:
5
[Optional(1), nil, nil, Optional(4), Optional(5)]
5
[Optional(1), nil, nil, Optional(4), Optional(5), nil]
6
any ideas from you?