Dictionaries and Sets in Swift: Key-Value Storage, Lookups, Default Values, Set Operations and Choosing the Right Collection

Swift 55 min min read Updated: Nov 21, 2026 Beginner
Dictionaries and Sets in Swift: Key-Value Storage, Lookups, Default Values, Set Operations and Choosing the Right Collection
Beginner Topic 2 of 3

Dictionaries

A dictionary stores values by key. Looking up a key returns an optional, because the key may be missing.

swift var stock = ["apple": 5, "kiwi": 0] print(stock["apple"] as Any, stock["mango"] as Any) stock["mango"] = 12 // add stock["kiwi"] = 3 // update stock["apple"] = nil // remove print(stock.count, stock["mango", default: 0], stock["pear", default: 0])
Output

Optional(5) nil | 2 12 0

Looping

swift let ages = ["Asha": 21, "Ravi": 25, "Meena": 19] for (name, age) in ages.sorted(by: { $0.key < $1.key }) { print(name, age) } print(ages.keys.sorted(), ages.values.reduce(0, +))
Output

Asha 21 | Meena 19 | Ravi 25 | ["Asha", "Meena", "Ravi"] 65

Dictionaries have no guaranteed order, so sort the keys when you need a stable printout.

Counting and Grouping

swift let word = "banana" var counts: [Character: Int] = [:] for ch in word { counts[ch, default: 0] += 1 } print(counts.sorted { $0.key < $1.key }) let grouped = Dictionary(grouping: ["ant", "bee", "bat", "ape"], by: { $0.first! }) print(grouped.sorted { $0.key < $1.key })
Output

[(key: "a", value: 3), (key: "b", value: 1), (key: "n", value: 2)] | [(key: "a", value: ["ant", "ape"]), (key: "b", value: ["bee", "bat"])]

Sets

A set keeps unique values and checks membership very quickly.

swift let a: Set = [1, 2, 3, 4] let b: Set = [3, 4, 5] print(a.union(b).sorted(), a.intersection(b).sorted(), a.subtracting(b).sorted()) print(a.contains(2), Set([1, 1, 2, 2, 3]).count)
Output

[1, 2, 3, 4, 5] [3, 4] [1, 2] | true 3

Choosing a Collection

NeedUse
Ordered list, duplicates allowedArray
Look up by keyDictionary
Unique items or fast containsSet

Common Mistakes

  • Assuming a dictionary keeps insertion order
  • Force unwrapping a dictionary lookup that may be nil
  • Using an array when a set would be faster for contains checks

Practice

  1. Count how many times each word appears in a sentence
  2. Find the common items of two sets
  3. Group a list of names by first letter

Conclusion

Use dictionaries for lookups by key and sets for unique values. Remember that lookups return optionals.

Quick Summary: Dictionary; counting; grouping; sets; choosing.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators