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:
Syntax
var name: Set<Type> = [value1, value2]
name.insert(value)
name.contains(value)
setA.union(setB)
setA.intersection(setB)
setA.subtracting(setB)
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
// Declare a constant `uniqueNumbers` (a `Set`), set to `[1, 2, 2, 3, 3, 3]`
let uniqueNumbers: Set = [1, 2, 2, 3, 3, 3]
// Print `uniqueNumbers.count` to the console
print(uniqueNumbers.count)
// Print `uniqueNumbers.contains(2)` to the console
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
// Declare a constant `evens` (a `Set`), set to `[2, 4, 6, 8]`
let evens: Set = [2, 4, 6, 8]
// Declare a constant `smallNumbers` (a `Set`), set to `[1, 2, 3, 4]`
let smallNumbers: Set = [1, 2, 3, 4]
// Print `evens.intersection(smallNumbers).sorted()` to the console
print(evens.intersection(smallNumbers).sorted())
// Print `evens.union(smallNumbers).sorted()` to the console
print(evens.union(smallNumbers).sorted())
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
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: