#43: Set Operations in Swift

Swift’s Set type comes with the standard operations you expect from set algebra.

let a: Set = [1, 2, 3]
let b: Set = [3, 4, 5]

a.union(b)                // [1, 2, 3, 4, 5]
a.intersection(b)         // [3]
a.subtracting(b)          // [1, 2]
a.symmetricDifference(b)  // [1, 2, 4, 5]

These methods make intent much clearer than manually looping and checking membership.

For relationship checks, you also have helpers like isSubset(of:), isSuperset(of:) and isDisjoint(with:).


I'm also on Twitter and GitHub.

Subscribe via RSS.