Dictionaries & Sets
Two more essential collections. By the end of this lesson you'll map keys to values with [K: V] dictionaries (handling optional lookups safely), and use Set for unique values and fast membership tests.
Learn Dictionaries & Sets in our free Swift course — a beginner-friendly interactive lesson with worked examples, a practice exercise and a quick reference.
Part of the free Swift course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
- • Declare dictionaries with the [Key: Value] syntax
- • Add, update, and remove key-value pairs
- • Handle optional lookups with if let , ?? , and [key, default:]
- • Create Set s for unique, unordered values
- • Combine and compare sets with union , intersection , subtracting
1️⃣ Dictionaries: Key → Value
A dictionary maps unique keys to values, written [Key: Value] . Add or update with subscript assignment. Crucially, looking up a key returns an optional — it's nil when the key isn't present.
Unwrap lookups safely and iterate over pairs:
2️⃣ Sets: Unique & Unordered
A Set<Element> stores each value at most once, with no order. Inserting a duplicate does nothing, which makes sets ideal for de-duplicating and fast contains checks.
3️⃣ Set Operations
Sets support clean algebra: union (everything), intersection (in both), subtracting (in one but not the other), and symmetricDifference (in exactly one).
Your turn. Fill in the blanks, then run it and check the output.
Pro Tips
- 💡 Use [key, default: x] to read-with-fallback and even count cleanly: counts[w, default: 0] += 1 .
- 💡 De-dupe instantly by wrapping an array in Set(array) .
- 💡 Sets are unordered — call .sorted() when you need stable output.
- 💡 Membership is fast. For "is x in this collection?" checks, a Set beats scanning an array.
Common Errors (and the fix)
- "Value of optional type 'Int?' must be unwrapped" — a key lookup is optional. Use if let , ?? , or [key, default:] .
- Wrong dictionary type syntax — it's [String: Int] (colon), not [String, Int] .
- Expecting set order — sets are unordered; relying on iteration order is a bug. Sort first.
- "Cannot use mutating member on immutable value" — insert needs a var set, not a let .
📋 Quick Reference
Task
Code
Result
Dictionary
var d: [String: Int] = [:]
empty map
Set / update
d["a"] = 1
add/update key
Lookup
d["a"]
Int? (optional)
Default
d["a", default: 0]
0 if missing
Set
var s: Set = [1, 2]
unique values
Membership
s.contains(1)
true / false
Frequently Asked Questions
Mini-Challenge: Vote Counter
Build it, run it, and check your output against the example in the comments.
🎉 Lesson Complete!
- ✅ Dictionaries map keys to values with [Key: Value]
- ✅ Key lookups return optionals — handle them with if let , ?? , or [key, default:]
- ✅ Sets store unique, unordered values; duplicates collapse
- ✅ Combine sets with union , intersection , subtracting
- ✅ Next lesson: Tuples
Practice quiz
How do you write the type of a dictionary mapping String keys to Int values?
Swift dictionary types are written [Key: Value], e.g. [String: Int].
What does looking up a value by key, like dict["x"], return?
- An optional (Value?) — nil if the key is absent
- The value directly
- Always nil
- A Bool
Answer: An optional (Value?) — nil if the key is absent. Subscripting by key returns an optional because the key may not exist.
Why does dictionary key lookup return an optional?
- For speed
- To save memory
- It doesn't — it returns the value
- Because the key might not be present
Answer: Because the key might not be present. A missing key yields nil, so the result type is Value?.
What kind of collection is a Set?
- An ordered list with duplicates
- An unordered collection of unique values
- A key-value map
- A fixed-size array
Answer: An unordered collection of unique values. A Set stores unique, unordered elements.
What happens if you insert a value already in a Set?
- It has no effect — sets keep values unique
- It's added again (duplicate)
- The set is cleared
- It crashes
Answer: It has no effect — sets keep values unique. Sets ignore duplicate insertions, keeping each value only once.
How do you write the type of a Set of Strings?
A set type is written Set<Element>, e.g. Set<String>.
Which Set method tests membership?
- set.has(x)
- set.contains(x)
- set.includes(x)
- set.member(x)
Answer: set.contains(x). contains(_:) returns a Bool indicating membership.
What does the intersection of two sets contain?
- All elements from both
- Elements in the first but not the second
- Nothing
- Only elements present in BOTH sets
Answer: Only elements present in BOTH sets. intersection keeps only the elements common to both sets.
Are the elements of a Set guaranteed to be in a particular order?
- Yes, insertion order
- No — a Set is unordered
- Yes, sorted order
- Yes, reverse order
Answer: No — a Set is unordered. Sets are unordered; iteration order is not guaranteed.
How do you safely provide a default when a dictionary key is missing?
Subscript with a default: dict["k", default: 0] returns 0 if the key is absent.