Learn

There are several options for removing key-value pairs from a Swift dictionary.

In Swift, the keyword nil describes something as being empty or having no value. If we were to set the value of a key to nil, the key-value pair would be removed from the dictionary:

dictionaryName[Key] = nil

Consider the following dictionary bookShelf that stores key-value pairs of titles and authors for books we currently own:

var bookShelf = [ "Goodnight Moon": "Margaret Wise Brown", "The BFG": "Roald Dahl", "Falling Up": "Shel Silverstein" ]

Imagine being part of a book drive and donating one of the books. To keep bookShelf accurate, let’s remove the key-value pair "The BFG": "Roald Dahl" by setting the value of "The BFG" to nil:

bookShelf["The BFG"] = nil

We can also remove a single key-value pair using the .removeValue() method:

dictionaryName.removeValue(forKey: Key)

The .removeValue() method takes a name of a key after forKey: to know which key-value pair to remove.

If we were to use the .removeValue() method to delete an element from bookShelf, our code would look like this:

bookShelf.removeValue(forKey: "The BFG")

If we wanted to delete every key-value pair in a dictionary at once, we could use the .removeAll() method:

dictionaryName.removeAll()

Note how this method does not take any parameters; simply append .removeAll() to an existing dictionary.

If we needed to remove all the values in bookShelf, our syntax would be:

bookShelf.removeAll()

Instructions

1.

Check out the dictionary rainbowHex in Color.swift. The dictionary should only contain the names and hex values for the colors of the rainbow, but it currently has a few extra elements.

Remove the key-value pair "maroon": "#800000" from rainbowHex using nil.

2.

Remove the key-value pair "pink": "#ffc0cb" from rainbowHex using the .removeValue() method.

3.

Remove all the elements from rainbowHex using .removeAll().

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Already have an account?