Set.union() / intersection() / subtracting()
Swift's Set supports set operations such as union, intersection, and difference, letting you express mathematical set logic in a straightforward way.
Method List
| Method | Description |
|---|---|
| union(_:) | Returns the union of two sets (all elements found in either set). |
| intersection(_:) | Returns the intersection of two sets (elements common to both sets). |
| subtracting(_:) | Returns the difference of two sets (elements in the receiver but not in the given set). |
| symmetricDifference(_:) | Returns the symmetric difference — elements found in one set but not both. |
| isSubset(of:) | Returns whether the set is a subset of the specified set. |
| isSuperset(of:) | Returns whether the set is a superset of the specified set. |
| isDisjoint(with:) | Returns whether the two sets have no elements in common. |
Sample Code
let setA: Set<Int> = [1, 2, 3, 4, 5]
let setB: Set<Int> = [3, 4, 5, 6, 7]
// Union: elements in A or B
let unionSet = setA.union(setB)
print("Union: \(unionSet.sorted())")
// Intersection: elements in both A and B
let intersectionSet = setA.intersection(setB)
print("Intersection: \(intersectionSet.sorted())")
// Difference: elements in A but not in B
let subtractingSet = setA.subtracting(setB)
print("Difference (A - B): \(subtractingSet.sorted())")
// Symmetric difference: elements in one set but not both
let symDiffSet = setA.symmetricDifference(setB)
print("Symmetric difference: \(symDiffSet.sorted())")
// Check subset and superset
let small: Set<Int> = [1, 2, 3]
print("small is a subset of setA: \(small.isSubset(of: setA))")
print("setA is a superset of small: \(setA.isSuperset(of: small))")
// Disjoint sets (no common elements)
let setC: Set<Int> = [8, 9, 10]
print("setA and setC are disjoint: \(setA.isDisjoint(with: setC))")
// Mutating methods (modify the set in place)
var mutableSet: Set<Int> = [1, 2, 3]
mutableSet.formUnion([3, 4, 5])
print("After formUnion: \(mutableSet.sorted())")
Notes
Set operation methods come in two forms: non-mutating versions that return a new set (union, intersection, etc.) and mutating versions that modify the set in place (formUnion, formIntersection, etc.).
Set operations are useful for removing duplicates or finding common elements between datasets — for example, finding the products that both user A and user B have in common. Non-mutating methods do not change the original set, so you must capture the return value to use the result (unless you use a mutating variant).
For basic Set operations, see Set.insert() / remove() / contains().
If you find any errors or copyright issues, please contact us.