Start learning free

LESSON 131 OF 678 · DICTIONARIES

Deleting a Key in Swift

Lesson

TL ; DR:

removeValue(forKey:) deletes a key and its value from a dictionary.


var toys = ["ball": 3, "doll": 2, "kite": 1]
toys.removeValue(forKey: "kite")

print(toys.count)   // 2


Full lesson:

Sometimes an entry has to go. A shop stops selling an item. A player leaves the game.

Call removeValue(forKey:) on the dictionary with the key. The key and its value go away together.

The count drops by 1. The key is gone, so toys["kite"] is now nil.

It also returns the deleted value, as an optional. For a missing key it returns nil, and nothing changes.

Setting a key to nil deletes it too, as in toys["kite"] = nil.

The dictionary must be a var. A let dictionary can't change.

Watch out: after the delete, toys["kite"]! crashes the program. There is no value left to unwrap.


Your task

A pet shop counts what it has for sale in animals. Each key is a kind of animal. Its value is how many the shop has.

The last rabbit just went home with a family. Delete the key "rabbit" from animals.

Then print animals.count again. The code at the bottom checks if any rabbits are left.

Expected output:

3
2
No rabbits left
STEP 1 OF 2
    Ctrl + Enter to check