0
0
Swiftprogramming~15 mins

Set creation and operations in Swift - Deep Dive

Choose your learning style9 modes available
Overview - Set creation and operations
What is it?
A set is a collection of unique values with no specific order. In Swift, sets help you store items where duplicates are not allowed. You can create sets, add or remove items, and perform operations like union or intersection to combine or compare sets. Sets are useful when you want to quickly check if something is included or to work with groups of unique things.
Why it matters
Without sets, managing unique items would be harder and slower, especially when checking if an item exists or combining groups without duplicates. Sets make these tasks fast and simple, saving time and reducing mistakes. For example, if you want to track unique visitors or ingredients without repeats, sets are the perfect tool.
Where it fits
Before learning sets, you should understand basic collections like arrays and dictionaries. After sets, you can explore more advanced collection operations, algorithms that use sets, or how sets compare to other data structures like lists or maps.
Mental Model
Core Idea
A set is like a bag that holds only unique items, letting you quickly add, remove, and compare groups without duplicates.
Think of it like...
Imagine a basket where you put fruits, but you never allow two of the same fruit inside. If you try to add an apple again, it won't go in because the basket only keeps one of each kind.
┌───────────────┐
│     Set       │
│ ┌───────────┐ │
│ │ Apple     │ │
│ │ Banana    │ │
│ │ Orange    │ │
│ └───────────┘ │
└───────────────┘
Operations:
Union: Combine baskets without duplicates
Intersection: Fruits common to both baskets
Difference: Fruits in one basket but not the other
Build-Up - 7 Steps
1
FoundationCreating a Basic Set
🤔
Concept: How to create a set with unique items in Swift.
You create a set by listing items inside square brackets and specifying the type as Set. For example: let fruits: Set = ["Apple", "Banana", "Orange"] This creates a set of strings with three unique fruits.
Result
A set containing Apple, Banana, and Orange with no duplicates.
Understanding how to create a set is the first step to using unique collections efficiently.
2
FoundationAdding and Removing Items
🤔
Concept: How to add or remove items from a set after creation.
Sets are mutable if declared with var. You can add items using insert() and remove items using remove(): var fruits: Set = ["Apple", "Banana"] fruits.insert("Orange") fruits.remove("Banana") Now fruits contains Apple and Orange.
Result
The set updates to include Orange and exclude Banana.
Knowing how to change sets after creation lets you manage unique collections dynamically.
3
IntermediateChecking Membership and Count
🤔
Concept: How to check if an item is in a set and count items.
Use contains() to check if an item exists and count to see how many items are in the set: let fruits: Set = ["Apple", "Banana", "Orange"] let hasApple = fruits.contains("Apple") // true let total = fruits.count // 3
Result
You get true for Apple existing and count 3 for total items.
Fast membership checks and knowing size are key benefits of sets.
4
IntermediatePerforming Set Operations
🤔Before reading on: do you think union adds duplicates or removes them? Commit to your answer.
Concept: How to combine or compare sets using union, intersection, and difference.
Swift sets support operations: - union: combines two sets without duplicates - intersection: finds common items - subtracting: removes items found in another set Example: let setA: Set = [1, 2, 3] let setB: Set = [3, 4, 5] setA.union(setB) // {1, 2, 3, 4, 5} setA.intersection(setB) // {3} setA.subtracting(setB) // {1, 2}
Result
You get combined, common, or unique items depending on the operation.
Understanding these operations unlocks powerful ways to compare and merge unique data.
5
IntermediateUsing Set Algebra for Logic
🤔Before reading on: do you think symmetricDifference keeps items in both sets or only unique to each? Commit to your answer.
Concept: How to use symmetricDifference to find items unique to each set, excluding shared ones.
symmetricDifference returns items in either set but not in both: let setA: Set = [1, 2, 3] let setB: Set = [3, 4, 5] setA.symmetricDifference(setB) // {1, 2, 4, 5} This excludes the common item 3.
Result
You get items unique to each set, excluding shared ones.
Knowing symmetricDifference helps when you want to find differences without overlap.
6
AdvancedSet Performance and Hashing
🤔Before reading on: do you think sets store items in order or use a special method to find them quickly? Commit to your answer.
Concept: How sets use hashing to store and find items efficiently without order.
Sets use a hash function to assign each item a unique number. This lets Swift quickly check if an item is in the set without searching every item. Because of hashing, sets do not keep items in order. This makes operations like contains() very fast.
Result
Sets provide fast membership checks but do not preserve order.
Understanding hashing explains why sets are fast but unordered, which affects how you use them.
7
ExpertCustom Types in Sets and Hashable Protocol
🤔Before reading on: do you think you can put any custom object in a set without extra work? Commit to your answer.
Concept: How to make your own types work in sets by conforming to Hashable.
To store custom objects in a set, they must conform to the Hashable protocol. This means you provide a way to compute a hash value and check equality: struct Person: Hashable { let name: String let id: Int } Now you can create sets of Person objects. Swift uses your hash and equality to manage uniqueness.
Result
Custom types can be stored in sets if they implement hashing and equality.
Knowing how to make custom types hashable lets you use sets beyond simple types, expanding their power.
Under the Hood
Swift sets are implemented as hash tables. Each item is passed through a hash function that produces a number used as an index in an internal storage array. When adding or checking items, Swift uses this hash to jump directly to the storage location instead of scanning all items. If two items have the same hash (a collision), Swift uses a method to handle it, like storing multiple items in a bucket. This design makes operations like insert, remove, and contains very fast on average.
Why designed this way?
Sets were designed to provide fast membership tests and uniqueness guarantees. Using hashing allows constant-time average operations, which is much faster than scanning lists. Alternatives like arrays or linked lists are slower for these tasks. The tradeoff is that sets do not preserve order and require types to be hashable, but the speed benefits outweigh these limits for many uses.
┌───────────────┐
│   Item to add │
└──────┬────────┘
       │ hash function
       ▼
┌───────────────┐
│  Hash value   │
└──────┬────────┘
       │ index into
       ▼
┌───────────────┐
│ Storage array │
│ ┌───────────┐ │
│ │ Bucket 1  │ │
│ │ Bucket 2  │ │
│ │ Bucket 3  │ │
│ └───────────┘ │
└───────────────┘
If collision:
Multiple items stored in same bucket

Operations like contains() use the same hash to find the bucket quickly.
Myth Busters - 4 Common Misconceptions
Quick: Does a set keep the order of items as you add them? Commit to yes or no.
Common Belief:Sets keep items in the order you add them, like arrays.
Tap to reveal reality
Reality:Sets do not keep any order. The items are stored based on their hash values, so the order can seem random.
Why it matters:Assuming order can cause bugs when you rely on the sequence of items from a set.
Quick: Can you add duplicate items to a set and have them stored twice? Commit to yes or no.
Common Belief:You can add duplicates to a set and they will be stored multiple times.
Tap to reveal reality
Reality:Sets automatically ignore duplicates. Adding an item already in the set does nothing.
Why it matters:Expecting duplicates can lead to incorrect counts or logic errors.
Quick: Can any type be stored in a set without extra work? Commit to yes or no.
Common Belief:You can put any type in a set without needing to do anything special.
Tap to reveal reality
Reality:Only types that conform to the Hashable protocol can be stored in sets.
Why it matters:Trying to store non-hashable types causes compile errors and confusion.
Quick: Does symmetricDifference return all items from both sets including shared ones? Commit to yes or no.
Common Belief:symmetricDifference returns all items from both sets, including those they share.
Tap to reveal reality
Reality:symmetricDifference returns only items unique to each set, excluding shared items.
Why it matters:Misunderstanding this leads to wrong results when comparing sets.
Expert Zone
1
Hash collisions are rare but possible; understanding how Swift handles them prevents subtle bugs in custom hash implementations.
2
Sets do not guarantee order, but you can convert them to arrays and sort if order matters.
3
Using sets with large data requires careful hash function design to maintain performance.
When NOT to use
Avoid sets when you need to preserve the order of items or allow duplicates. Use arrays or linked lists instead. Also, if your data type cannot conform to Hashable, sets are not an option without extra work.
Production Patterns
In real-world Swift apps, sets are used for fast membership checks like tracking unique user IDs, filtering duplicates from data, and performing complex set algebra for permissions or feature flags. Developers often combine sets with dictionaries for efficient lookups and use custom hashable structs to model domain data.
Connections
Hash Tables
Sets are implemented using hash tables internally.
Understanding hash tables explains why sets are fast for membership and uniqueness.
Mathematical Set Theory
Programming sets mirror mathematical sets with operations like union and intersection.
Knowing math set theory helps grasp set operations and their properties in code.
Database Indexing
Sets and database indexes both use hashing or trees to quickly find unique records.
Recognizing this connection shows how data structures optimize search in different fields.
Common Pitfalls
#1Trying to store a custom class in a set without making it Hashable.
Wrong approach:class Person { var name: String init(name: String) { self.name = name } } var people: Set = [] // Error: Person does not conform to Hashable
Correct approach:class Person: Hashable { var name: String init(name: String) { self.name = name } static func == (lhs: Person, rhs: Person) -> Bool { return lhs.name == rhs.name } func hash(into hasher: inout Hasher) { hasher.combine(name) } } var people: Set = [] // Works fine
Root cause:Swift requires types in sets to be hashable to ensure uniqueness and fast lookup.
#2Assuming sets keep the order of insertion and relying on it.
Wrong approach:let fruits: Set = ["Banana", "Apple", "Orange"] for fruit in fruits { print(fruit) // Assumes order Banana, Apple, Orange }
Correct approach:let fruits: Set = ["Banana", "Apple", "Orange"] for fruit in fruits.sorted() { print(fruit) // Prints in sorted order: Apple, Banana, Orange }
Root cause:Sets are unordered collections; relying on order causes unpredictable behavior.
#3Using insert() on a let constant set expecting it to change.
Wrong approach:let fruits: Set = ["Apple", "Banana"] fruits.insert("Orange") // Error: Cannot use mutating member on immutable value
Correct approach:var fruits: Set = ["Apple", "Banana"] fruits.insert("Orange") // Works fine
Root cause:Only sets declared with var are mutable and can be changed after creation.
Key Takeaways
Sets store unique items without any order, making them perfect for membership tests and removing duplicates.
Swift sets require items to conform to Hashable, enabling fast lookup through hashing.
Set operations like union, intersection, and difference let you combine and compare groups easily.
Sets do not preserve order; if order matters, convert to an array and sort.
Understanding how sets work internally helps you use them efficiently and avoid common mistakes.