Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 146 ยท Collections

Dictionary Patterns

Practical Swift dictionary recipes - counting with reduce(into:), grouping with Dictionary(grouping:by:), mapValues, inverting, nested dictionaries, lookup tables and memoization.

Once you know how a dictionary works, a small set of recipes covers most of what you will do with one: count things, group things, transform the values, flip keys and values, nest dictionaries inside dictionaries, and use a dictionary as a lookup table or a cache. Each recipe replaces a loop with a few clear lines, and each has a trap that professionals learn to avoid.

This lesson assumes you have read Dictionaries. All the examples sort their results before printing, because dictionary order is random from one run to the next.

Counting

The classic pattern uses the default: subscript. A second spelling uses reduce(into:), which hands the closure a mutable accumulator so the dictionary is built without copies.

Swift Counting letters two ways

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Often you want the most frequent item. A dictionary has no order, so sort the pairs. Break ties explicitly, or two items with the same count can swap places from run to run:

Swift Top words with a tie-breaker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

max(by:) on a dictionary returns whichever tied pair it meets first, and "first" depends on the random order, so use it only for the value, never for the key, unless the maximum is unique.

Grouping

Dictionary(grouping:by:) takes a sequence and a closure that computes a key for each element, and returns [Key: [Element]]. Elements within a group keep their original order.

Swift Dictionary(grouping:by:)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Combine grouping with mapValues to summarize each group. That is the "group by and aggregate" of SQL in two steps:

Swift Group, then summarize

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Transforming values and keys

mapValues keeps the keys and transforms the values; compactMapValues also discards nil results, which is perfect for parsing; filter keeps the matching pairs; map returns an array of whatever you choose. To transform keys, build a new dictionary.

Swift mapValues, compactMapValues and rekeying

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Inverting a dictionary

Swapping keys and values is easy when the values are unique, and a trap when they are not. Two entries with the same value would produce the same new key, and uniqueKeysWithValues traps. Decide what duplicates mean: keep one, or collect all of them in an array.

Swift Inverting with unique values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Swift Inverting when values repeat

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first form sorts each list before printing, because grades.keys is in random order, so the order inside each group is random too.

Nested dictionaries

A dictionary can hold dictionaries: [String: [String: Int]] might map a student to a subject to a score. Reading chains optionals; writing needs the default: subscript at every level.

Swift A dictionary of dictionaries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Deep nesting gets awkward quickly. When the structure has a fixed shape, a struct with named properties is clearer and safer than dictionaries of dictionaries; save the nested form for data whose keys are genuinely dynamic.

Dictionaries as lookup tables

A dictionary replaces a long if/else or switch chain when the mapping is data rather than logic. Closures are values, so a dictionary can even map names to behavior. The table is passed to the function as a parameter, because a top-level let in main.swift belongs to the main actor in Swift 6 and a plain function may not read it (the next sections show that kind of diagnostic):

Swift A table of operations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Memoization

A dictionary also serves as a cache. A function that recomputes the same answer many times can store results by input. Swift 6 does not allow a global mutable cache without isolation, so pass it in inout or keep it in a local scope:

Swift Memoized Fibonacci

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Without the cache the same call would take billions of steps; with it, each value from 2 to 50 is computed once, so the cache holds 49 entries.

A mistake: global mutable state (fails on purpose)

It is tempting to hide the cache in a global variable. In Swift 6 language mode the compiler checks that such state cannot be raced on:

Swift Global cache under Swift 6 (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler rejects it with two errors: main actor-isolated var 'cache' can not be mutated from a nonisolated context (line 5) and main actor-isolated var 'cache' cannot be accessed from outside of the actor (line 4). In main.swift, top-level variables belong to the main actor, and square is not on it. Fixes: keep the dictionary local and pass it inout, wrap it in an actor, protect it with a Mutex, or, for a single-threaded script, mark it nonisolated(unsafe) and take responsibility yourself. Concurrency is covered later in the course.

Two-sum: the classic lookup trick

Given numbers and a target, find two that add up to it. The brute-force answer compares every pair (O(n squared)). With a dictionary of "numbers seen so far" it is one pass:

Swift Two-sum with a dictionary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Dictionary(grouping: [1, 2, 3, 4], by: { $0 % 2 }) produce?

    grouping:by: returns [Key: [Element]], collecting elements under the key the closure returns.
  2. 2. Why should a frequency ranking include a tie-breaker?

    The dictionary's order is random per process, so tied entries need an explicit secondary key to be deterministic.
  3. 3. What is the problem with inverting ["a": 1, "b": 1] using uniqueKeysWithValues?

    That initializer requires unique keys. Use Dictionary(grouping:) or uniquingKeysWith: when values repeat.
  4. 4. Which method transforms the values and drops entries for which the closure returns nil?

    compactMapValues is to mapValues what compactMap is to map.
  5. 5. How do you safely add to a nested [String: [String: Int]] for a student who may not exist yet?

    The default subscript inserts an empty inner dictionary when needed and lets you mutate it in place.

Summary

  • Count with dict[key, default: 0] += 1 or reduce(into:); rank by sorting the pairs with a tie-breaker.
  • Dictionary(grouping:by:) collects elements under computed keys; follow with mapValues to aggregate.
  • mapValues and compactMapValues keep the keys; build a new dictionary to change keys.
  • Invert with uniqueKeysWithValues only when values are unique, otherwise group or give a merge rule.
  • Nested dictionaries need default: at every level to write; prefer structs when the shape is fixed.
  • Dictionaries serve as lookup tables and memo caches; in Swift 6 keep the cache local, inout or isolated.

Next: Collection Protocols