Lesson 24Collections
Set Operations
Combining & Comparing Sets
Sets have powerful operations for combining, comparing, and finding differences between collections. These come from mathematical set theory!
The Four Main Operations
Union
All elements from both sets
{1,2,3}∪{3,4,5}={1,2,3,4,5}
Intersection
Only common elements
{1,2,3}∩{3,4,5}={3}
Subtracting
Elements in first, not second
{1,2,3}-{3,4,5}={1,2}
Symmetric Difference
Elements in either, not both
{1,2,3}△{3,4,5}={1,2,4,5}
Relationship Checks
.isSubset(of:)All my elements in other?
.isSuperset(of:)Contains all of other?
.isDisjoint(with:)No common elements?
Real-World Uses
- Union: "All students in any club"
- Intersection: "Students in BOTH math AND science"
- Subtracting: "Students in math but NOT science"
- Symmetric: "Students in exactly ONE club"
main.swift
// Two sets for comparison
let setA: Set = [1, 2, 3, 4, 5]
let setB: Set = [4, 5, 6, 7, 8]
// UNION - All elements from both sets
let union = setA.union(setB)
print("Union: \(union)")
// {1, 2, 3, 4, 5, 6, 7, 8}
// INTERSECTION - Only common elements
let intersection = setA.intersection(setB)
print("Intersection: \(intersection)")
// {4, 5}
// DIFFERENCE - Elements in A but not in B
let difference = setA.subtracting(setB)
print("A - B: \(difference)")
// {1, 2, 3}
// SYMMETRIC DIFFERENCE - Elements in either, not both
let symmetricDiff = setA.symmetricDifference(setB)
print("Symmetric: \(symmetricDiff)")
// {1, 2, 3, 6, 7, 8}
// Real-world example: Students in clubs
let mathClub: Set = ["Alice", "Bob", "Charlie", "Diana"]
let scienceClub: Set = ["Bob", "Diana", "Eve", "Frank"]
// Students in both clubs
let bothClubs = mathClub.intersection(scienceClub)
print("Both clubs: \(bothClubs)")
// ["Bob", "Diana"]
// Students in at least one club
let anyClub = mathClub.union(scienceClub)
print("Any club: \(anyClub)")
// Only math, not science
let onlyMath = mathClub.subtracting(scienceClub)
print("Only math: \(onlyMath)")
// ["Alice", "Charlie"]
// Subset and superset checking
let smallSet: Set = [1, 2]
let bigSet: Set = [1, 2, 3, 4, 5]
print(smallSet.isSubset(of: bigSet)) // true
print(bigSet.isSuperset(of: smallSet)) // true
print(smallSet.isDisjoint(with: setB)) // true (no common)
// Comparing sets
let setC: Set = [1, 2, 3]
let setD: Set = [3, 2, 1]
print(setC == setD) // true (order doesn't matter!)
// In-place operations
var mySet: Set = [1, 2, 3]
mySet.formUnion([4, 5]) // Modifies mySet
mySet.formIntersection([2, 3, 4]) // Keeps only common
print(mySet) // {2, 3, 4}Try It Yourself!
Create two sets of favorite foods for you and a friend. Find foods you both like, foods only you like, and all foods combined!