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
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.
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.
popitem() is a built-in method in python dictionary that is used to remove and return the last key-value pair from the dict.
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)
dict.removeValue(forKey: willRemoveKey)
Swift 5, Swift 4, and Swift 3:
x.removeValue(forKey: "MyUndesiredKey")
Cheers
dict.removeValue(forKey: willRemoveKey)
Or you can use the subscript syntax:
dict[willRemoveKey] = nil
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