Sets
Set[T] is an unordered collection of unique values. Like Dictionary, the element type must conform to Hashable.
Creating
let tags: Set[String] = ["urgent", "pending", "review"];
let empty: Set[Int] = Set();
Set literals use the same [a, b, c] syntax as arrays — the type annotation is what tells the compiler which to make.
Membership
let tags: Set[String] = ["urgent", "pending", "review"];
tags.contains("urgent"); // true
tags.contains("draft"); // false
Constant-time lookup, since Sets are hash-backed.
Inserting and removing
var tags: Set[String] = [];
tags.insert("urgent");
tags.insert("urgent"); // no-op; already present
tags.remove("urgent");
Inserting an existing value is a silent no-op — that's the point of a set. (insert returns a Bool telling you whether the value was newly added, and remove returns whether it was present.)
Set algebra
let a: Set[Int] = [1, 2, 3];
let b: Set[Int] = [3, 4, 5];
a.union(b); // {1, 2, 3, 4, 5}
a.intersection(b); // {3}
a.difference(b); // {1, 2}
a.isSubset(of: b); // false
These operations don't mutate; they return a new set.
Iteration
let tags: Set[String] = ["urgent", "pending", "review"];
for tag in tags {
println(tag);
}
Order is unspecified.
When to reach for Set vs Array
- Set when membership testing, deduplication, or set algebra is the primary operation, and order doesn't matter.
- Array when order matters, duplicates are allowed, or you need indexed access.
If you find yourself calling array.contains(...) a lot, the data probably wanted to be a Set.