Sets
A set is a group of unique items with no duplicates and no particular order, like a bag where you can only have one of each kind of marble.
In this page:
Creating a Set
A Set is created either from an array literal with explicit type annotation, or with Set([...]), and automatically removes duplicate values.
Example: Creating a Set
let uniqueNumbers: Set = [1, 2, 2, 3, 3, 3]
print(uniqueNumbers.count)
print(uniqueNumbers.contains(2))
Login to try C/C++/Java/PHP code in the editor
Set Operations
Sets support mathematical operations like .union(), .intersection(), and .subtracting() to combine or compare two sets.
Example: Set Operations
let evens: Set = [2, 4, 6, 8]
let smallNumbers: Set = [1, 2, 3, 4]
print(evens.intersection(smallNumbers).sorted())
print(evens.union(smallNumbers).sorted())
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Assuming a set preserves insertion order like an array; sets are explicitly unordered.
- Adding a duplicate value expecting the set to grow; duplicates are automatically ignored.
- Using a set for a type that isn't
Hashable; every element type in aSetmust conform toHashable.
Chapter Summary
- A
Setstores unique values of the same type with no defined order, written asSet<Type>. - Adding a duplicate value has no effect since sets automatically enforce uniqueness.
- Sets support fast membership testing with
.contains(). - Set operations like union, intersection, and subtraction combine sets mathematically.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: