noiréCat noiréCat - 1 month ago 14
Swift Question

How to remove pairs from dictionary in Swift at specific index?

How to use

remove(at: DictionaryIndex<Key, Value>)
to remove pairs from dictionary in Swift?

Answer

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. 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.
Comments