Sets in Swift
Deduplication plus algebra: union, intersection, subtracting.
// Sets deduplicate and speak algebra.
let racedSaturday: Set = ["Kestrel", "Sable", "Petrel"]
let racedSunday: Set = ["Sable", "Brant"]
print("Sailed both days: \(racedSaturday.intersection(racedSunday))")
print("Whole fleet: \(racedSaturday.union(racedSunday).count) boats")
print("Saturday only: \(racedSaturday.subtracting(racedSunday).sorted())")
var protests: Set<String> = []
protests.insert("Sable")
protests.insert("Sable")
print("Protests filed: \(protests.count)")
How it works
Setliterals deduplicate on construction.intersectionandunionanswer membership questions.- A second
insertof the same member changes nothing.
Keywords and builtins used here
Stringcountinsertletprintsortedvar
The run, in numbers
- Lines
- 12
- Characters to type
- 477
- Tokens
- 120
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 111 seconds.
Step 3 of 3 in Collections, step 15 of 27 in Language basics.