Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a key-value pair from swift dictionary?

I want to remove a key-value pair from a dictionary like in the example.

var dict: Dictionary<String,String> = [:]
//Assuming dictionary is added some data.
var willRemoveKey = "SomeKey"
dict.removePair(willRemoveKey) //that's what I need
like image 867
do it better Avatar asked Sep 29 '15 14:09

do it better


People also ask

Can you remove key-value pairs from a dictionary and if so how?

To delete a key, value pair in a dictionary, you can use the del method. A disadvantage is that it gives KeyError if you try to delete a nonexistent key. So, instead of the del statement you can use the pop method. This method takes in the key as the parameter.

How do you get rid of a key in a dictionary?

Because key-value pairs in dictionaries are objects, you can delete them using the “del” keyword. The “del” keyword is used to delete a key that does exist. It raises a KeyError if a key is not present in a dictionary. We use the indexing notation to retrieve the item from the dictionary we want to remove.

Which function will delete the last inserted key-value pair from the dictionary?

popitem() is a built-in method in python dictionary that is used to remove and return the last key-value pair from the dict.


3 Answers

You can use this:

dict[willRemoveKey] = nil

or this:

dict.removeValueForKey(willRemoveKey)

The only difference is that the second one will return the removed value (or nil if it didn't exist)

Swift 3

dict.removeValue(forKey: willRemoveKey)
like image 65
Kametrixom Avatar answered Oct 26 '22 08:10

Kametrixom


Swift 5, Swift 4, and Swift 3:

x.removeValue(forKey: "MyUndesiredKey")

Cheers

like image 37
Sasho Avatar answered Oct 26 '22 08:10

Sasho


dict.removeValue(forKey: willRemoveKey)

Or you can use the subscript syntax:

dict[willRemoveKey] = nil
like image 23
Fantini Avatar answered Oct 26 '22 09:10

Fantini