Swift: Removing a key-value pair from a dictionary

Updated: May 8, 2023 By: Khue Post a comment

This concise article shows you a couple of different ways to remove a certain key-value pair from a dictionary in Swift. Without any further ado (like talking about the history of Swift and iOS), let’s get our hands dirty with code.

Using the removeValue(forKey:) method

The removeValue(forKey:) method removes the given key and its associated value from your dictionary. It returns the value that was removed or nil if the key was not present in the dictionary.

Example:

var sites = ["www.slingacademy.com": "Learn Programming and Data Science"]
if let oldValue = sites.removeValue(forKey: "www.slingacademy.com") {
    print("The value '\(oldValue)' was removed.")
} else {
    print("No value found for that key.")
}

Output:

The value 'Learn Programming and Data Science' was removed.

In case you want to remove all elements from a dictionary, use the removeAll() method. This method removes all key-value pairs from the dictionary. It has an optional parameter keepingCapacity that indicates whether the dictionary should keep its underlying buffer. If you pass true for this parameter, the operation preserves the buffer capacity that the collection has, otherwise, the buffer is released. The default value is false.

Example:

var animals = ["cat": "meow", "dog": "woof", "cow": "moo"]

print(animals.count) 
// Prints 3

animals.removeAll()
print(animals.count) 
// Prints 0

Using the subscript syntax

You can use the subscript syntax to delete a key-value pair from a dictionary by assigning the value to nil as shown in the example below:

var myDict = [
    "name": "John Doe",
    "age": "99",
    "job": "iOS Developer"
]

myDict["age"] = nil
myDict["job"] = nil

print(myDict)

Output:

["name": "John Doe"]