Introduction
Dictionaries store key-value pairs where each key is unique, letting you look up a value quickly by its associated key. Sets store unique elements with no defined order and no associated values. Both collections require their key or element type to conform to the Hashable protocol, which lets Swift use a hash-based structure internally for fast lookups, insertions, and removals rather than scanning the whole collection.
Cricket analogy: A scorecard is like a dictionary: each player's name is a unique key mapping to their runs, so you look up Kohli's score instantly instead of scanning every entry on the sheet.
Syntax
var dict: [String: Int] = ["a": 1, "b": 2]
var mySet: Set<Int> = [1, 2, 3]
var emptyDict: [String: String] = [:]
var emptySet = Set<String>()Explanation
Both dictionaries and sets are unordered — iterating over them does not guarantee any particular sequence. Subscript access on a dictionary, such as dict["a"], always returns an Optional value (Int? in this example) because the key might not exist; this forces you to safely unwrap the result with optional binding or nil-coalescing rather than assuming presence. Sets are ideal for fast membership checks (.contains()) and support classic set algebra operations like .union(_:) to combine two sets, .intersection(_:) to find common elements, and .subtracting(_:) to remove elements found in another set.
Cricket analogy: Checking if Root is in today's playing XI is a .contains() set check, while .intersection() finds players who featured in both this Ashes and the last one, and squad["Root"] returns an optional since he might be rested.
Example
var ages: [String: Int] = ["Alice": 30, "Bob": 25]
ages["Carol"] = 40
let aliceAge: Int? = ages["Alice"]
print(aliceAge ?? -1)
print(ages["Dave"] ?? -1)
let setA: Set<Int> = [1, 2, 3]
let setB: Set<Int> = [2, 3, 4]
print(setA.union(setB).sorted())
print(setA.intersection(setB).sorted())
print(setA.subtracting(setB).sorted())Output
30
-1
[1, 2, 3, 4]
[2, 3]
[1]Key Takeaways
- Dictionaries store unordered key-value pairs; keys must be Hashable and unique.
- Subscripting a dictionary always returns an Optional value.
- Sets store unordered, unique elements and require Hashable elements.
- Sets excel at fast membership checks with
.contains(). .union,.intersection, and.subtractingimplement classic set algebra.
Practice what you learned
1. What type does `dict["a"]` return for a `[String: Int]` dictionary?
2. What protocol must dictionary keys and set elements conform to?
3. Which set method returns elements present in both sets?
4. Are Swift dictionaries ordered?
5. What is a key benefit of using a Set instead of an Array for membership checks?
Was this page helpful?
You May Also Like
Arrays in Swift
Learn how Swift arrays store ordered, mutable collections of values and how to manipulate them safely.
Collection Operations in Swift (map, filter, reduce)
Master Swift's functional-style collection operations — map, filter, reduce, compactMap, and sorted.
Optionals in Swift
Optionals let a Swift variable represent either a value or the absence of one, forming the basis of Swift's null-safety.
Nil Coalescing Operator in Swift
The `??` operator supplies a default value when an optional is nil, in a single concise expression.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics