Start learning free

LESSON 129 OF 678 · DICTIONARIES

Checking for a Key in Swift

Lesson

TL ; DR:

A lookup gives nil when the key is missing. So dict[key] != nil asks whether a dictionary has a key.


let capitals: [String: String] = ["France": "Paris", "Japan": "Tokyo"]

if capitals["Japan"] != nil {
    print(capitals["Japan"]!)   // Tokyo
}

if capitals["Spain"] == nil {
    print("No Spain")           // No Spain
}


Full lesson:

You met this in Optionals & Unwrapping. capitals["Spain"] gives nil, and ! on it crashes the program.

capitals["Spain"] != nil is true when "Spain" is a key. == nil asks the opposite.

Inside the first if, the ! is safe. The if just checked the key.

if let does both at once. if let city = capitals["Japan"] checks the key and gives you its value.

A value is not a key

A lookup uses only the keys. capitals["Paris"] is nil, because "Paris" is a value.

A key must match exactly, upper and lower case too. capitals["japan"] is nil.


Your task

In pets, each key is a pet's name, and its value is the pet's kind.

First, check whether "Tom" is a key of pets. If it is, print Tom is a followed by Tom's kind.

Then check that "cat" is not a key, with == nil. If so, print cat is not a key.

"cat" is in pets, but only as a value. It is Tom's kind.

Expected output:

Tom is a cat
cat is not a key
STEP 1 OF 2
    Ctrl + Enter to check