Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 146 ยท Collections

Dictionaries

Learn Swift dictionaries - creating, optional subscripts, default values, updating and removing, merging, keys and values views, iteration order, Hashable keys and duplicate-key traps.

A dictionary stores key-value pairs and finds the value for a key almost instantly. A phone book maps names to numbers; a price list maps product codes to prices; a word counter maps words to counts. Whenever you catch yourself writing a loop that searches an array for "the entry whose id is 42", a dictionary is the tool you wanted.

In Swift the type is Dictionary<Key, Value>, written [Key: Value]. Keys must be unique and Hashable, values can be anything, and the order of the pairs is not defined. This lesson shows how to create dictionaries, read and write them (including the optional that every lookup returns), supply defaults, remove entries, merge two dictionaries, view the keys and values, and iterate safely. The practical recipes (counting, grouping, inverting) are in the next lesson, Dictionary Patterns.

Creating a dictionary

Swift Creating 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.

An empty dictionary literal is [:] (compare with [] for arrays). Dictionary(uniqueKeysWithValues:) builds one from a sequence of (key, value) pairs, and it is only safe if the keys really are unique; we will see what happens when they are not.

Reading: the subscript returns an optional

Looking up a key that does not exist is a normal situation, not a bug, so the subscript returns an optional: the value if the key is present, nil if not. This is the opposite of array subscripts, which trap on a bad index.

Swift Optional lookups

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 three common ways to handle the optional: if let when you only act on a hit, ?? when there is a sensible fallback, and guard let when the code cannot continue without it. Do not force-unwrap (capitals["Chile"]!) unless you have just proven the key exists; a missing key crashes the program.

Default values

The subscript has a second form: dict[key, default: value]. It returns the default when the key is missing, and it is not optional. When used on the left of an assignment, it inserts the default first, which makes counting idioms one line long:

Swift Subscript with a default

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.

Reading with a default does not add the key. Only mutation does, and it does it in a single lookup (efficient), unlike the two lookups of if dict[k] == nil { dict[k] = 0 }.

Adding, updating and removing

Assign to a subscript to add or replace. Assign nil to remove. The method forms return useful information.

Swift Add, replace, remove

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.

Because assigning nil removes the entry, a dictionary whose value type is itself optional ([String: Int?]) is confusing: dict["a"] = nil removes the key rather than storing a nil value. Avoid optional values; use an enum or a sentinel when you need "present but empty".

keys and values

dict.keys and dict.values are lightweight views, not arrays. They have their own types (Dictionary.Keys and Dictionary.Values), so convert with Array(...) or sorted() when you need an array.

Swift Working with keys and 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.

filter on a dictionary returns a dictionary (since Swift 4), while map returns an array. To transform values and keep the keys, use mapValues; compactMapValues also drops the entries where your closure returns nil. Lookup by value (first(where:)) is a linear scan, unlike lookup by key.

Iterating, and why order is not stable

for (key, value) in dict gives each pair as a tuple (key:, value:). The order is unspecified, and Swift deliberately randomizes the hash seed for each process, so the same program can visit the entries in a different order the next time it runs. That is a security feature (it defends against attacks that flood hash tables with colliding keys), and it is also a classic source of flaky tests.

Swift Never rely on dictionary order

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.

If you need a particular order, sort the pairs (the result is an array of tuples), or keep the keys in an array alongside the dictionary. Never "fix" a test by assuming the order you saw once.

Do not add or remove entries while iterating the same dictionary variable. Iteration works on a snapshot (value semantics), so your mutations do not affect the loop, but the code is easy to misread. Collect the keys first, or build the result with filter.

Merging dictionaries

merge(_:uniquingKeysWith:) and merging(_:uniquingKeysWith:) combine two dictionaries. When both contain a key, your closure decides which value wins (or how to combine them). There is deliberately no default, because the right choice depends on the data.

Swift Merging with a conflict rule

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.

Duplicate keys: the trap in the initializer

Dictionary(uniqueKeysWithValues:) promises its input has no repeated keys. If it does, the program stops with a fatal error. When the data may contain duplicates (anything coming from a file or a user), choose the variant that says how to resolve them: Dictionary(_:uniquingKeysWith:).

Swift Duplicate keys (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 program prints building from 3 pairs, then stderr shows Fatal error: Duplicate values for key: 'a' and the process ends with a signal (SIGILL). The fixed version decides what a duplicate means:

Swift Resolving duplicate keys

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.

Custom key types

Any Hashable type can be a key: strings, integers, enums without associated values (automatically), and structs whose stored properties are hashable. Use a small struct instead of a tuple, because tuples are not Hashable.

Swift A struct as a dictionary key

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.

Performance notes

  • Lookup, insert and remove are O(1) on average, as for a Set.
  • A dictionary is value-semantic with copy-on-write, so passing it around is cheap until one copy mutates.
  • Values are stored by the dictionary; if a value is a large struct, mutate it in place through the subscript (dict[k]?.items.append(x)) rather than copying it out and back in.
  • keys.contains(k) is O(1) (it uses the hash), but values.contains(v) is O(n).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of ages["Ada"] when ages is [String: Int]?

    The key might be absent, so the lookup returns an optional Int.
  2. 2. What does counts[word, default: 0] += 1 do when word is not yet a key?

    The default 0 is used as the starting value, 1 is added, and the result is stored under the new key.
  3. 3. Which statement about dictionary iteration order is true?

    Swift randomizes hashing per process. Sort the pairs when you need a stable order.
  4. 4. What happens with Dictionary(uniqueKeysWithValues: [("a", 1), ("a", 2)])?

    That initializer requires unique keys. Use Dictionary(_:uniquingKeysWith:) when duplicates are possible.
  5. 5. How do you remove the entry for key k?

    Assigning nil through the subscript removes the pair; removeValue(forKey:) does the same and returns the removed value.

Summary

  • [Key: Value] maps unique Hashable keys to values; the empty dictionary is [:].
  • The subscript returns an optional; handle it with if let, ?? or guard let, and use [key, default:] for counters and accumulators.
  • Assign nil or call removeValue(forKey:) to delete; updateValue(_:forKey:) returns the old value.
  • keys and values are views; filter returns a dictionary, mapValues keeps keys, map returns an array.
  • Iteration order is random per process: sort before printing, comparing or testing.
  • merging(_:uniquingKeysWith:) combines dictionaries; Dictionary(uniqueKeysWithValues:) traps on duplicate keys.

Next: Dictionary Patterns