Anonymous contributor's avatar
Anonymous contributor
Anonymous contributor's avatar
Anonymous contributor
Published May 8, 2023
Contribute to Docs

The .removeValue() method will remove a key-value pairing from a dictionary based on a given key. If the key exists in the dictionary, the method will return the removed value. However, if the key is not found, the method will return nil.


dictionaryInstance.removeValue(forKey: key)

The dictionaryInstance is the dictionary in which the key-value pairing will be removed. The key parameter is the key to remove.


In the example below, the fruitBasket dictionary is checked to see if the key Apples exists. If it does, it will remove that key and print the corresponding value. If it doesn’t, a value of nil is returned.

var fruitBasket = [
if let removedValue = fruitBasket.removeValue(forKey: "Apples") {
print(removedValue) // Output: 3
} else {
print("The key 'Apples' does not exist in the dictionary.")

All contributors

Looking to contribute?

Learn Swift on Codecademy