How to remove elements from a dictionary in Swift?

In this article, I show you four ways to remove elements from a dictionary:

  1. The “removeValue(forKey:)” method:
  2. The “removeAll()” method
  3. The subscipt syntax
  4. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *