In this article, I show you four ways to remove elements from a dictionary:
- The “removeValue(forKey:)” method:
- The “removeAll()” method
- The subscipt syntax
- The “remove(at:)” method
Given is the following dictionary:
var myDict = ["apple": 10, "banana": 20, "orange": 30]
The “removeValue(forKey:)” method
myDict.removeValue(forKey: "apple") print(myDict) // Output: ["banana": 20, "orange": 30]
The “removeAll()” method
myDict.removeAll() print(myDict) //Output: [:]
- In this example, we remove all key-value pairs from the dictionary using the “removeAll()” method.
The subscript syntax
You can also use the subscript syntax to set the value of a key to nil and remove it from the dictionary:
myDict["apple"] = nil print(myDict) // Output: ["banana": 20, "orange": 30]
The “remove(at:)” method
myDict.remove(at: myDict.index(forKey: "apple")!) print(myDict) // Output: ["banana": 20, "orange": 30]
Quick notes
- Both the “removeValue(forKey:)” and the “removeAll()” methods modify the original dictionary.
- If you want to remove elements from the dictionary but keep a copy of the original, you can create a new dictionary and copy only the elements you want to keep.
- It’s important to note that if you try to remove a key that does not exist in the dictionary, nothing will happen and the dictionary will not be modified.
You may also want to read this:
- How to know about the number of elements in a dictionary in Swift?
- How to update elements in a dictionary in Swift?
- The “.count” property and the “.append()”, “.insert()” and “.remove()” methods in Swift
- What are “.count”, “.isEmpty”, “.insert()”, “remove()”, “.removeAll()” and “.contains()” used for in Swift?