Swift Dictionary - Removing Key-Value Pairs

Here we will explain how to remove key-value pairs from a Swift Dictionary.

Removing a Key-Value Pair with removeValue()

In Swift, you can remove a key-value pair from a Dictionary using the removeValue() method.

The syntax is like dictionary.removeValue(forKey: "Key"), where you specify the key to remove.

The removeValue() method returns the removed value, so if you need the deleted value, you can assign the return value to a variable.


Let's remove a key-value pair from a Dictionary using removeValue():

var dict = ["Key1": "value1", "Key2": "value2", "Key3": "value3"]
print(dict)

let removed = dict.removeValue(forKey: "Key1")
print(dict)
print(removed ?? "Nothing is removed.")

The output is as follows. The key-value pair for Key1 has been removed from dict, and the removed value value1 has been stored in removed.

["Key2": "value2", "Key3": "value3", "Key1": "value1"]
["Key2": "value2", "Key3": "value3"]
value1

Removing All Key-Value Pairs with removeAll()

To remove all key-value pairs from a Swift Dictionary, use the removeAll() method.

Let's remove all elements with removeAll():

var dict = ["Key1": "value1", "Key2": "value2", "Key3": "value3"]
print(dict)

dict.removeAll()
print(dict)

The output is as follows. All key-value pairs have been removed.

["Key3": "value3", "Key1": "value1", "Key2": "value2"]
[:]

That wraps up how to remove key-value pairs from a Swift Dictionary.