Start learning free

LESSON 130 OF 678 · DICTIONARIES

Reading a Key That May Be Missing in Swift

Lesson

TL ; DR:

dict[key, default: 0] gives the key's value, or 0 when the key is missing.


let points: [String: Int] = ["Ana": 7]

print(points["Ana", default: 0])   // 7
print(points["Ben", default: 0])   // 0


Full lesson:

A missing key often means "none yet". A player with no points yet has 0 points.

points["Ben"] gives nil here. Its type is Int?, a number or nil. And ! on nil crashes the program.

With default:, a missing key gives the default instead. Either way, you get a plain Int.

Reading this way doesn't add the key. points still has one key afterwards.

The ?? from Optionals & Unwrapping works too, as in points["Ben"] ?? 0.


Your task

stock counts the fruit in a shop. The code reads and prints the pears.

There are no plums yet. Read "plums" with default: 0. Store it in plums.

Then print the plums line, the same way as the pears line.

Expected output:

We have 2 pears
We have 0 plums
STEP 1 OF 2
    Ctrl + Enter to check