Sets and Tuples
Prerequisites: Dictionaries
Two more ways to group values.
Sets — unique values, no order
A set holds each value at most once and has no defined order. Checking whether a set contains a value is very fast, even for huge sets.
var tags: Set = ["swift", "ios", "swift", "xcode"]
print(tags.count)
print(tags.contains("ios"))
tags.insert("macos")
tags.remove("xcode")
print(tags.sorted())
let a: Set = [1, 2, 3, 4]
let b: Set = [3, 4, 5]
print(a.intersection(b).sorted())
print(a.union(b).sorted())
print(a.subtracting(b).sorted())
3
true
["ios", "macos", "swift"]
[3, 4]
[1, 2, 3, 4, 5]
[1, 2]
The duplicate "swift" is stored once. Like dictionaries, sets are
unordered — use sorted() for stable output.
Use a set when you only care about membership ("have we seen this before?"), and an array when order or duplicates matter.
Tuples — a few values grouped together
A tuple bundles a fixed number of values, which can be different types:
let point = (x: 3, y: 4)
print(point.x)
let (name, age) = ("Ada", 36)
print("\(name) is \(age)")
func minMax(_ numbers: [Int]) -> (min: Int, max: Int) {
(numbers.min() ?? 0, numbers.max() ?? 0)
}
let range = minMax([4, 9, 1])
print("\(range.min) to \(range.max)")
3
Ada is 36
1 to 9
Tuples are great for returning a couple of values from a function. For anything you pass around widely, define a struct instead (Level 2) — it can have methods and is easier to extend.
Common mistakes
- Expecting a set to keep insertion order.
- Using big tuples (four or more values) where a struct would be clearer.