Set algebra helps you combine or compare groups of unique items easily. It lets you find all items together, only common items, or items that are different.
0
0
Set algebra (union, intersection, difference) in Swift
Introduction
You want to combine two lists of unique names without duplicates.
You need to find common friends between two people.
You want to see what items are missing from one list compared to another.
You are filtering data to find overlaps or differences.
You want to quickly check if two groups share any elements.
Syntax
Swift
let unionSet = setA.union(setB) let intersectionSet = setA.intersection(setB) let differenceSet = setA.subtracting(setB)
Sets in Swift hold unique values with no order.
union() adds all unique elements from both sets.
Examples
This combines all unique numbers from both sets.
Swift
let setA: Set<Int> = [1, 2, 3] let setB: Set<Int> = [3, 4, 5] let unionSet = setA.union(setB) print(unionSet)
This finds numbers present in both sets.
Swift
let setA: Set<Int> = [1, 2, 3] let setB: Set<Int> = [3, 4, 5] let intersectionSet = setA.intersection(setB) print(intersectionSet)
This finds numbers in setA but not in setB.
Swift
let setA: Set<Int> = [1, 2, 3] let setB: Set<Int> = [3, 4, 5] let differenceSet = setA.subtracting(setB) print(differenceSet)
Sample Program
This program shows how to get all unique fruits from both sets (union), fruits common to both (intersection), and fruits only in the first set (difference). We sort the sets before printing to see the items in order.
Swift
import Foundation let setA: Set<String> = ["apple", "banana", "cherry"] let setB: Set<String> = ["banana", "dragonfruit", "apple"] let unionSet = setA.union(setB) let intersectionSet = setA.intersection(setB) let differenceSet = setA.subtracting(setB) print("Union:", unionSet.sorted()) print("Intersection:", intersectionSet.sorted()) print("Difference:", differenceSet.sorted())
OutputSuccess
Important Notes
Sets do not keep order, so use sorted() to print in order.
union() combines all unique elements from both sets.
intersection() finds only elements present in both sets.
subtracting() finds elements in the first set not in the second.
Summary
Use union to combine all unique items from two sets.
Use intersection to find common items between sets.
Use difference (subtracting) to find items in one set but not the other.