Thuta Learning
BasicProgrammingbeginner

Dictionaries

Relax. We'll talk through this in plain words — no textbook voice.

Dictionary is a collection that stores data as key-value pairs. It's useful for things like user profiles, settings, country-capital mappings, or product price tables. Where an array cares mostly about order, a dictionary cares about looking things up by key.

swift
var capitals = [
    "Myanmar": "Naypyidaw",
    "Japan": "Tokyo"
]

if let myanmarCapital = capitals["Myanmar"] {
    print("Capital of Myanmar is \(myanmarCapital)")
}

capitals["Thailand"] = "Bangkok"
print("Total countries: \(capitals.count)")

When you grab a value from a dictionary by key, the result is an optional — because that key might not actually exist. That's why using if let to print the value only when it exists is the safe approach.

You should see
Capital of Myanmar is Naypyidaw Total countries: 3

Easy traps

  • Force-unwrapping with capitals["Korea"]! can crash your app if the key doesn't exist.
Dictionaries | Thuta Learning