typestar

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

  1. Set literals deduplicate on construction.
  2. intersection and union answer membership questions.
  3. A second insert of the same member changes nothing.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Collections, step 15 of 27 in Language basics.

← Previous Next →

Sets in other languages