← Back to Swift Course | Chapter 6: Collections | Lesson 3 of 7

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.

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

markup
let uniqueNumbers: Set = [1, 2, 2, 3, 3, 3]
print(uniqueNumbers.count)
print(uniqueNumbers.contains(2))

Set Operations

Sets support mathematical operations like .union(), .intersection(), and .subtracting() to combine or compare two sets.

Example: Set Operations

markup
let evens: Set = [2, 4, 6, 8]
let smallNumbers: Set = [1, 2, 3, 4]
print(evens.intersection(smallNumbers).sorted())
print(evens.union(smallNumbers).sorted())
Common Mistakes
  1. Assuming a set preserves insertion order like an array; sets are explicitly unordered.
  2. Adding a duplicate value expecting the set to grow; duplicates are automatically ignored.
  3. Using a set for a type that isn't Hashable; every element type in a Set must conform to Hashable.
Chapter Summary
  • A Set stores unique values of the same type with no defined order, written as Set<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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.