Set Operations in Swift
In this article, we will explain how to perform set operations with Swift Set.
Getting the Intersection of Sets with intersection()
By using the intersection() method of a Swift Set, you can get a new Set that contains only the elements common to both Sets.
Let's actually use the intersection() method to get a Set containing the common elements of two Sets.
let set1: Set = [1, 2, 3, 4, 5, 6, 7, 8]
let set2: Set = [3, 6, 9, 12]
let set3 = set1.intersection(set2)
print(set3)
The output will be as follows. The Set contains 3 and 6, which exist in both set1 and set2.
[3, 6]
Getting the Union of Sets with union()
By using the union() method of a Swift Set, you can get a new Set containing the union of two Sets.
Let's actually use the union() method to get a Set containing the union of two Sets.
let set1: Set = [1, 2, 3, 4, 5, 6, 7, 8]
let set2: Set = [3, 6, 9, 12]
let set3 = set1.union(set2)
print(set3)
The output will be as follows. The Set contains the union of set1 and set2.
[9, 4, 2, 3, 5, 7, 8, 12, 6, 1]
Getting the Subtraction of Sets with subtracting()
By using the subtracting() method of a Swift Set, you can get a new Set containing the subtraction of one Set from another.
Let's actually use the subtracting() method to get a Set containing the subtraction of two Sets.
let set1: Set = [1, 2, 3, 4, 5, 6, 7, 8]
let set2: Set = [3, 6, 9, 12]
let set3 = set1.subtracting(set2)
print(set3)
The output will be as follows. The Set contains the elements of set1 except for the common elements 3 and 6.
[4, 7, 8, 1, 5, 2]
Getting the Symmetric Difference of Sets with symmetricDifference()
By using the symmetricDifference() method of a Swift Set, you can get a new Set containing the symmetric difference of two Sets.
Let's actually use the symmetricDifference() method to get a Set containing the symmetric difference of two Sets.
let set1: Set = [1, 2, 3, 4, 5, 6, 7, 8]
let set2: Set = [3, 6, 9, 12]
let set3 = set1.symmetricDifference(set2)
print(set3)
The output will be as follows. The Set contains the elements of the union of set1 and set2, minus the intersection of set1 and set2.
[4, 8, 5, 1, 12, 9, 2, 7]
That wraps up how to perform set operations with Swift Set.