Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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

like image 704
Shakespear Avatar asked Mar 10 '23 23:03

Shakespear


1 Answers

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.
like image 186
Martin R Avatar answered Apr 09 '23 01:04

Martin R