Swift Sets

A set is an unordered collection of unique values. Unlike an array, a set never holds duplicates. Think of it as a bag of distinct items — toss in the same item twice and it still appears only once inside the bag.

Creating a Set

Set Literal

let colors: Set<String> = ["Red", "Green", "Blue"]
let numbers: Set = [1, 2, 3, 4, 5]

You must write the type annotation Set<String> or Set explicitly. Without it, Swift infers an array.

Empty Set

var tags = Set<String>()
var ids = Set<Int>()

Diagram: Array vs Set

Array (ordered, allows duplicates):   Set (unordered, unique only):
["A", "B", "A", "C"]                 {"A", "B", "C"}
  0    1    2    3                    no index, no duplicates

Adding and Removing

var fruits: Set<String> = ["Apple", "Banana"]

fruits.insert("Cherry")
print(fruits)   // {"Apple", "Banana", "Cherry"} (order may vary)

fruits.insert("Apple")   // Already exists — no change
print(fruits.count)      // Output: 3

fruits.remove("Banana")
print(fruits)   // {"Apple", "Cherry"}

Checking Membership

let allowedUsers: Set = ["Alice", "Bob", "Carol"]

if allowedUsers.contains("Alice") {
    print("Access granted.")
}
// Output: Access granted.

print(allowedUsers.contains("Dave"))   // Output: false

contains on a Set is extremely fast regardless of size. Arrays scan from the beginning; sets jump directly to the answer.

Set Properties

let primes: Set = [2, 3, 5, 7, 11]

print(primes.count)     // Output: 5
print(primes.isEmpty)   // Output: false
print(primes.first!)    // Output: varies (unordered)

Iterating Over a Set

for color in colors {
    print(color)
}
// Output (order may vary): Red Green Blue

Sorted Iteration

for color in colors.sorted() {
    print(color)
}
// Output: Blue Green Red

Set Operations

Sets support mathematical operations that are perfect for working with groups.

Diagram: Set Operations

Set A = {1, 2, 3, 4}        Set B = {3, 4, 5, 6}

Union (A | B)                Intersection (A & B)
{1, 2, 3, 4, 5, 6}          {3, 4}
All items from both          Only shared items

Subtracting (A - B)          Symmetric Difference (A XOR B)
{1, 2}                       {1, 2, 5, 6}
A's items not in B           Items in A or B, but not both

union

let a: Set = [1, 2, 3, 4]
let b: Set = [3, 4, 5, 6]

let combined = a.union(b)
print(combined)   // {1, 2, 3, 4, 5, 6}

intersection

let shared = a.intersection(b)
print(shared)   // {3, 4}

subtracting

let onlyA = a.subtracting(b)
print(onlyA)   // {1, 2}

symmetricDifference

let unique = a.symmetricDifference(b)
print(unique)   // {1, 2, 5, 6}

Set Membership Tests

Subset

let small: Set = [1, 2]
let big: Set = [1, 2, 3, 4]

print(small.isSubset(of: big))    // true — all of small is inside big
print(big.isSuperset(of: small))  // true — big contains all of small

Disjoint

let evens: Set = [2, 4, 6]
let odds: Set = [1, 3, 5]

print(evens.isDisjoint(with: odds))   // true — no items in common

Removing Duplicates From an Array Using a Set

Converting an array to a Set removes duplicates instantly.

let votes = ["Swift", "Kotlin", "Swift", "Python", "Swift"]
let unique = Array(Set(votes))
print(unique)   // ["Swift", "Kotlin", "Python"] (order may vary)

When to Use a Set vs Array

NeedUse
Ordered listArray
Unique items onlySet
Fast membership checkSet
Duplicates allowedArray
Mathematical group operationsSet

Summary

Sets store unique, unordered values. They provide instant membership checks with contains, and rich group operations like union, intersection, subtracting, and symmetricDifference. Use a Set when uniqueness matters and order does not.

Leave a Comment

Your email address will not be published. Required fields are marked *