Swift Sets
A set is an unordered collection of unique values. Use a set when you only care whether something is present, not where or how many times: the tags on a blog post, the IDs of users who liked a photo, the letters already guessed in a word game.
| Array | Set | Dictionary | |
|---|---|---|---|
| Ordered | yes | no | no |
| Duplicates allowed | yes | no | keys: no |
Fast contains |
no (checks one by one) | yes | yes (for keys) |
Creating a set
A set has no literal syntax of its own; you write an array literal and tell Swift you want a Set:
var colors: Set<String> = ["red", "green", "blue", "red"]
let numbers = Set([3, 1, 3, 2, 1])
var empty = Set<Int>()
print(colors.count) // the duplicate "red" was dropped
print(numbers.sorted())
print(empty.isEmpty)3
[1, 2, 3]
true
Note: Like dictionaries, sets have no stable order — printing a set directly can show a different order on each run. Use
sorted()whenever you display one.
Adding, removing and checking
var guessed: Set<Character> = []
for letter in "banana" {
let (inserted, _) = guessed.insert(letter)
print("\(letter): \(inserted ? "new" : "already guessed")")
}
print(guessed.contains("n"))
guessed.remove("b")
print(guessed.sorted())b: new
a: new
n: new
a: already guessed
n: already guessed
a: already guessed
true
["a", "n"]
insert returns a tuple telling you whether the value was actually new — handy for detecting duplicates.
Set operations
Sets shine when you combine them. Imagine two groups of students and the clubs they joined:
| Operation | Result |
|---|---|
a.union(b) |
everything in a or b |
a.intersection(b) |
only what is in both |
a.subtracting(b) |
what is in a but not in b |
a.symmetricDifference(b) |
what is in exactly one of them |
let chess: Set = ["Ana", "Ben", "Chen", "Dia"]
let robotics: Set = ["Chen", "Dia", "Eli"]
print("Any club: \(chess.union(robotics).sorted())")
print("Both clubs: \(chess.intersection(robotics).sorted())")
print("Only chess: \(chess.subtracting(robotics).sorted())")
print("Exactly one: \(chess.symmetricDifference(robotics).sorted())")Any club: ["Ana", "Ben", "Chen", "Dia", "Eli"]
Both clubs: ["Chen", "Dia"]
Only chess: ["Ana", "Ben"]
Exactly one: ["Ana", "Ben", "Eli"]
Each of these returns a new set. Mutating versions exist too: formUnion, formIntersection, subtract and formSymmetricDifference.
Comparing sets
let allPermissions: Set = ["read", "write", "delete"]
let editor: Set = ["read", "write"]
let guest: Set = ["comment"]
print(editor.isSubset(of: allPermissions))
print(allPermissions.isSuperset(of: editor))
print(editor.isDisjoint(with: guest))
print(editor == Set(["write", "read"]))true
true
true
true
Two sets are equal (==) when they contain the same elements — order never matters.
Removing duplicates from an array
Converting to a set and back is the quickest way to remove duplicates. But the original order is lost, so sort the result, or keep the first occurrence of each item with a "seen" set:
let visits = ["home", "about", "home", "blog", "about", "contact"]
let uniqueSorted = Set(visits).sorted()
print(uniqueSorted)
var seen = Set<String>()
var firstVisits: [String] = []
for page in visits where !seen.contains(page) {
seen.insert(page)
firstVisits.append(page)
}
print(firstVisits)["about", "blog", "contact", "home"]
["home", "about", "blog", "contact"]
Tip:
set.contains(x)is very fast even for millions of elements, whilearray.contains(x)must scan the array. If you test membership in a loop, a set is usually the better choice.
Test yourself
What does Set([1, 1, 2, 2, 3]).count return?
- 5
- 3
- 2
- 1
Which operation gives the elements that are in BOTH sets?
- union
- intersection
- subtracting
- symmetricDifference
Why do the examples call sorted() before printing a set?
- print() cannot print sets
- Sets are unordered, so the printed order could change between runs
- sorted() removes duplicates
- It converts the set to a dictionary