Sets store unique unordered elements; tuples group fixed numbers of values of possibly different types—lightweight alternatives to small structs.
Set operations
var tags: Set = ["swift", "ios", "swift"]
tags.insert("macos")
print(tags.count) // 3 — duplicates ignored
let a: Set = [1, 2, 3]
let b: Set = [3, 4, 5]
print(a.union(b))
Tuples
let pair = (name: "Ada", score: 98)
print(pair.name)
let (n, s) = pair
Important interview questions and answers
- Q: Set vs Array?
A: Set guarantees uniqueness and unordered membership tests in O(1) average; array preserves order and allows duplicates. - Q: Tuple vs struct?
A: Tuples are anonymous and best for small temporary groups; structs scale with methods, protocols, and clarity.
Self-check
- What happens if you insert a duplicate into a Set?
- How do you access named tuple elements?
Tip: Prefer structs over tuples when the grouped data grows beyond two or three fields.
Interview prep
- Set vs Array?
Set enforces uniqueness and unordered membership; array preserves order.
- Tuple vs struct?
Tuples for small anonymous groups; structs scale with methods and clarity.