How to use remove(at: DictionaryIndex<Key, Value>)
to remove pairs from a dictionary in Swift?
You can obtain the index of a key/value pair in a dictionary and then remove the entry:
var dict = ["foo": 1, "bar": 2, "baz": 3]
print(dict) // ["bar": 2, "baz": 3, "foo": 1]
if let idx = dict.index(forKey: "bar") {
dict.remove(at: idx)
print(dict) // ["baz": 3, "foo": 1]
}
However, indices of dictionary entries are of limited use because the order of the key/value pairs in a dictionary is unspecified, and inserting or deleting an entry invalidates all existing dictionary indices.
You would achieve the same result with
dict["bar"] = nil
or
dict.removeValue(forKey: "bar")
Those methods differ only in what they return:
dict["bar"] = nil
does not return a value.dict.removeValue(forKey: "bar")
returns the removed value
(as an optional) if the given key was present in the dictionary, and nil
otherwise.dict.remove(at: idx)
returns the removed key/value pair as a tuple.
The return value is not optional because it takes the index of an
existing entry as the argument.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With