Menu
Coddy logo textTech

Optional Lookup

Part of the Logic & Flow section of Coddy's Swift journey — lesson 13 of 56.

Dictionary subscripts always return an Optional: the value when the key exists, nil when it doesn't. Swift forces you to handle both cases.

let prices: [String: Int] = ["apple": 1, "bread": 3]
let p = prices["apple"]
print(p)                          // Optional(1)

Three idiomatic ways to deal with the optional. Pick the one that fits the situation.

1. if let: handle both branches explicitly:

if let p = prices["apple"] {
    print("apple costs \(p)")
} else {
    print("unknown")
}

2. nil-coalescing ??: provide a fallback inline:

let p = prices["olive"] ?? 0    // 0

3. subscript with default: identical result, but the default also stays put if you write back to that key:

var counts = ["a": 2]
counts["b", default: 0] += 1   // counts == ["a": 2, "b": 1]
challenge icon

Challenge

Easy

The dictionary prices is given. Read a single line of input: a comma-separated list of items the user wants to buy.

For each item, in input order, look it up in prices. Print one line per item:

  • <item> @ <price> when the item is in the dictionary
  • <item> not sold otherwise

After listing every item, print one final line: Total: <sum>. Treat missing items as costing 0 using the nil-coalescing operator.

For input apple,bread,olive,milk, the output is:

apple @ 1
bread @ 3
olive not sold
milk @ 4
Total: 8

Cheat sheet

Dictionary subscripts return an Optional — the value if the key exists, nil if not.

1. if let — handle both branches:

if let p = prices["apple"] {
    print("apple costs \(p)")
} else {
    print("unknown")
}

2. Nil-coalescing ?? — provide a fallback:

let p = prices["olive"] ?? 0    // 0

3. Subscript with default — fallback that also works on write:

var counts = ["a": 2]
counts["b", default: 0] += 1   // ["a": 2, "b": 1]

Try it yourself

let prices: [String: Int] = ["apple": 1, "bread": 3, "milk": 4]
let items = readLine()!.components(separatedBy: ",")

// TODO: per-item lookup; print '@ price' or 'not sold'; sum with ?? 0
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow