Remove an Item From a Dictionary in Swift

In this short tutorial, you will learn how to remove a single item from a dictionary in Swift as well as how to remove all items from a dictionary.

Create a New Dictionary

Let’s say you have created the following dictionary with a few key-value pairs in it.

var myDictionary = ["firstName": "Sergey", "lastName": "Kargopolov", "email":"[email protected]"]

To preview the values in this dictionary we can simply print them out.

// print to preview
print(myDictionary)

Now let’s learn how to remove one of the key-value pairs from this dictionary.

Remove Dictionary Item

To remove an item from a dictionary in Swift we can use a removeValue(forKey key: Key) function. For example:

// Remove item for a key
myDictionary.removeValue(forKey: "firstName")

The removeValue() function will actually return the value that was removed or nil if the key was not found in the dictionary. In the code snippet below an item is removed from a dictionary and the removed value is printed out.

// Remove item for a key
let removedValue = myDictionary.removeValue(forKey: "firstName")

if let removedValue = removedValue {
    print("We have just removed '\(removedValue)' from our dictionary")
}

or we can use if-else condition

// Remove item for a key
if let removedValue = myDictionary.removeValue(forKey: "firstName") {
    print("We have just removed '\(removedValue)' from our dictionary")
} else {
    print("Could not remove dictionary item")
}

Here is how the above code looks and works in Xcode Playground.

Remove Item from Dictionary in Swift

Remove All Items

To remove all items in a dictionary you can use the removeAll() function. For example:

myDictionary.removeAll()

Below is a more complete Swift code example that demonstrates how to create a new Dictionary and then how to remove all dictionary items.

//Create Dictionary
var myDictionary = ["firstName": "Sergey", "lastName": "Kargopolov", "email":"[email protected]"]

// print to preview
print(myDictionary)

// Remove all elements from a dictionary
myDictionary.removeAll()
 
// print dictionary to preview
print(myDictionary)

I hope this very tutorial with a little code example in Swift was helpful for you. Check out other Swift tutorials on this site or have a look at the below list of online video courses that teach Swift.

Leave a Reply

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