Skip to content

Swift Algorithms

Developer UtilitiesUtilitiesSwift

What it is

Apple's package of sequence and collection algorithms: chunking, windows, combinations, permutations, unique and product.

Extension methods on Sequence and Collection. Most are lazy, so chaining them does not allocate intermediate arrays.

Installation

.package(url: "https://github.com/apple/swift-algorithms.git", from: "1.2.0")

Getting started

The smallest useful thing you can do with it, and what each part means.

The commonly useful ones
import Algorithms

// Fixed-size batches — for paging or bulk API calls.
for batch in ids.chunks(ofCount: 100) {
    try await api.bulkFetch(Array(batch))
}

// Sliding windows, for deltas.
for pair in prices.windows(ofCount: 2) {
    print(pair.last! - pair.first!)
}

// Group runs of equal keys.
for (year, group) in books.chunked(on: \.year) { print(year, group.count) }

let unique = ids.uniqued()

for (row, col) in product(1...3, ["a", "b"]) { print(row, col) }

// Top n without sorting everything.
let topFive = scores.max(count: 5)
max(count:) uses a partial sort, so finding the top five of a million items does not require sorting all of them — a common and easily missed optimisation.

Advanced usage

Where the library earns its place over a simpler alternative.

Combinatorics and partitioning
for pair in items.combinations(ofCount: 2) { compare(pair[0], pair[1]) }

// Split by a predicate in one pass, in place.
let index = books.partition { $0.year < 1990 }
let modern = books[..<index]
let classic = books[index...]

let merged = Array(chain(firstPage, secondPage))

let trimmed = line.trimming { $0.isWhitespace }
partition mutates in place and returns the pivot index, so splitting a collection costs one pass and no extra allocation.

Errors and fixes

The failures you are most likely to hit, and what actually resolves them.

chunked(on:) produces more groups than expected
It groups consecutive elements only. Sort by the same key first.
Combinations are extremely slow
Combinatorial growth. combinations(ofCount:) over a large collection is exponential — filter first.

Best practices

  • Prefer these over hand-written loops — they are lazy and well tested.
  • Use chunks(ofCount:) for batching API calls rather than manual index arithmetic.
  • Use max(count:) instead of sorting when you only need the top few.
  • Remember chunked(on:) groups adjacent elements; sort first for global grouping.

Background

Why it exists, and what it was reacting to.

Companion to Swift Collections, this holds the algorithms that are broadly useful but not fundamental enough for the standard library — many mirroring Rust's Itertools or Python's itertools.