Swift Sets
A set is a collection that stores each value only once. Adding a value that is already present changes nothing.
Duplicates are dropped
The literal lists 2 twice, so the built set holds three values. The sorted line shows each value once.
let numbers = Set([3, 1, 2, 2])
print(numbers.count)
print(numbers.sorted())Checking membership
The value 2 is in the set, so contains answers true. The value 9 is absent, so contains answers false.
let numbers = Set([3, 1, 2])
print(numbers.contains(2))
print(numbers.contains(9))Inserting a duplicate changes nothing
Inserting 2 again leaves the count at 3. Inserting 4 then raises the count to 4.
var numbers = Set([3, 1, 2])
numbers.insert(2)
print(numbers.count)
numbers.insert(4)
print(numbers.count)
print(numbers.sorted())Union and intersection
Union holds every value from both sets. Intersection holds only the shared values, 2 and 3.
let a = Set([1, 2, 3])
let b = Set([2, 3, 4])
print(a.union(b).sorted())
print(a.intersection(b).sorted())Example
var points = Set([10, 20, 20, 30])
print(points.count)
points.insert(20)
print(points.count)
points.insert(40)
print(points.contains(40))
print(points.sorted())
let extra = Set([30, 40, 50])
print(points.union(extra).sorted())
print(points.intersection(extra).sorted())Key points
- A set holds unique values, with no duplicates.
- Duplicate values in a set literal are dropped when the set is built.
- The contains method reports whether a value is in a set.
- Inserting a value that is already present leaves the count unchanged.
- Union joins two sets into one set holding every value from both.
- Intersection builds a set holding only the values shared by both sets.
- The sorted method gives the values as an ordered array for printing.
In this example, the first line builds a set from a list where 20 appears twice, so the count prints 3. Inserting 20 again leaves the count at 3. Inserting 40 adds a new value, and the contains check prints true. The sorted line prints the four values in order. The union with extra prints every value from both sets. The intersection prints only 30 and 40, the values both sets share.
Note
A set keeps no fixed order for its values, so sorted output is the safe route for printed lines.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Swift Compiler
Exercise
What is the count of Set([5, 5, 6])?