TExcelTAD
Home › Swift › Swift Dictionaries

Swift Dictionaries

A dictionary stores key–value pairs. Instead of looking values up by position (like an array), you look them up by a unique key: a word and its definition, a username and its score, a country code and its name.

Creating a dictionary

The type is written [KeyType: ValueType]. Keys must be unique and hashable (strings, numbers, booleans, enums… all are).

swift · try it yourself
var capitals = ["France": "Paris", "Japan": "Tokyo", "Kenya": "Nairobi"]
let stock: [String: Int] = ["apples": 12, "pears": 0]
var empty: [String: Double] = [:]

print(capitals.count)
print(stock["apples"]!)
print(empty.isEmpty)
3
12
true

Reading values

Looking up a key returns an optional, because the key might not exist. Use ?? to supply a fallback, or provide a default: directly in the subscript:

swift · try it yourself
let ages = ["Mia": 31, "Leo": 27]

print(ages["Mia"] as Any)        // Optional(31)
print(ages["Zoe"] as Any)        // nil
print(ages["Zoe"] ?? 0)
print(ages["Leo", default: 0])

if let age = ages["Mia"] {
    print("Mia is \(age) years old")
}
Optional(31)
nil
0
27
Mia is 31 years old

Note: Unlike arrays, a missing dictionary key never crashes — you simply get nil.

Adding, updating and removing

swift · try it yourself
var inventory = ["pens": 10, "notebooks": 4]

inventory["erasers"] = 7          // add a new key
inventory["pens"] = 25            // update an existing key
inventory["notebooks", default: 0] += 1

let old = inventory.updateValue(3, forKey: "erasers")
print("erasers was \(old!)")

inventory["pens"] = nil           // remove by assigning nil
inventory.removeValue(forKey: "glue")  // removing a missing key is fine

for key in inventory.keys.sorted() {
    print("\(key): \(inventory[key]!)")
}
erasers was 7
erasers: 3
notebooks: 5

Iteration order is not guaranteed

Dictionaries are unordered. When you print one or loop over it, the order can change from one run of the program to the next. Whenever order matters, sort first:

swift · try it yourself
let population = ["Lagos": 15.4, "Cairo": 22.6, "Accra": 2.6, "Nairobi": 5.3]

// Sorted by key (alphabetical)
for (city, millions) in population.sorted(by: { $0.key < $1.key }) {
    print("\(city): \(millions)M")
}

print("---")

// Sorted by value, largest first
for (city, millions) in population.sorted(by: { $0.value > $1.value }) {
    print("\(city): \(millions)M")
}
Accra: 2.6M
Cairo: 22.6M
Lagos: 15.4M
Nairobi: 5.3M
---
Cairo: 22.6M
Lagos: 15.4M
Nairobi: 5.3M
Accra: 2.6M

sorted(by:) turns the dictionary into an array of (key, value) tuples in the order you choose. You'll learn the { $0.key < $1.key } closure syntax in the Closures chapter.

Useful properties and methods

Member Description
count, isEmpty number of pairs / whether there are none
keys, values collections of all keys / values
dict[key, default: v] read with a fallback, or modify in place
updateValue(_:forKey:) sets a value and returns the old one (optional)
removeValue(forKey:) removes and returns the value (optional)
mapValues { } new dictionary with transformed values
filter { } new dictionary with only matching pairs

Counting with a dictionary

A classic task: count how often each word appears. The default: subscript makes it a one-liner inside the loop:

swift · try it yourself
let text = "the cat and the hat and the bat"
var counts: [String: Int] = [:]

for word in text.split(separator: " ") {
    counts[String(word), default: 0] += 1
}

let doubled = counts.mapValues { $0 * 2 }
let frequent = counts.filter { $0.value > 1 }

for word in counts.keys.sorted() {
    print("\(word) → \(counts[word]!) (doubled: \(doubled[word]!))")
}
print("Frequent words: \(frequent.keys.sorted())")
and → 2 (doubled: 4)
bat → 1 (doubled: 2)
cat → 1 (doubled: 2)
hat → 1 (doubled: 2)
the → 3 (doubled: 6)
Frequent words: ["and", "the"]

Grouping values

Dictionary(grouping:by:) builds a dictionary of arrays from a list:

swift · try it yourself
let animals = ["ant", "bee", "bear", "cat", "cow", "camel"]
let byLetter = Dictionary(grouping: animals, by: { $0.first! })

for letter in byLetter.keys.sorted() {
    print("\(letter): \(byLetter[letter]!)")
}
a: ["ant"]
b: ["bee", "bear"]
c: ["cat", "cow", "camel"]

Tip: Like arrays, dictionaries are value types: assigning one to a new variable creates an independent copy.

Test yourself

What type does ages["Zoe"] have when ages is [String: Int]?

  1. Int
  2. Int? (an optional)
  3. String
  4. Bool

How do you remove the key "pens" from var inventory: [String: Int]?

  1. inventory["pens"] = 0
  2. inventory["pens"] = nil
  3. inventory.remove("pens")
  4. delete inventory["pens"]

Why should you sort a dictionary before printing its contents in a test or tutorial?

  1. Sorting makes it faster
  2. Dictionaries are unordered; iteration order can differ between runs
  3. print() requires sorted input
  4. Keys are stored in reverse order