Swift Algorithms is an open-source package of sequence and collection algorithms, along with their related types.
Read more about the package, and the intent behind it, in the announcement on swift.org.
Combinations / permutations
combinations(ofCount:): Combinations of a particular size of the elements in a collection.
permutations(ofCount:): Permutations of a particular size of the elements in a collection, or of the full collection.
rotate(subrange:toStartAt:): In-place rotation of elements.
stablePartition(subrange:by:): A partition that preserves the relative order of the resulting prefix and suffix.
chained(with:): Concatenates two collections with the same element type.
product(_:_:): Iterates over all the pairs of two collections; equivalent to nested
cycled(times:): Repeats the elements of a collection forever or a set number of times.
randomSample(count:using:): Randomly selects a specific number of elements from a collection.
randomStableSample(count:using:): Randomly selects a specific number of elements from a collection, preserving their original relative order.
uniqued(on:): The unique elements of a collection, preserving their order.
Other useful operations
chunked(on:): Eager and lazy operations that break a collection into chunks based on either a binary predicate or when the result of a projection changes.
indexed(): Iterate over tuples of a collection's indices and elements.
Adding Swift Algorithms as a Dependency
To use the
Algorithms library in a SwiftPM project,
add the following line to the dependencies in your
.package(url: "https://github.com/apple/swift-algorithms", from: "0.0.1"),
Algorithms is under active development,
source-stability is only guaranteed within minor versions (e.g. between
If you don't want potentially source-breaking package updates,
use this dependency specification instead:
.package(url: "https://github.com/apple/swift-algorithms", .upToNextMinor(from: "0.0.1")),
"Algorithms" as a dependency for your executable target:
let package = Package( // name, platforms, products, etc. dependencies: [ .package(url: "https://github.com/apple/swift-algorithms", from: "0.0.1"), // other dependencies ], targets: [ .target(name: "<target>", dependencies: [ .product(name: "Algorithms", package: "swift-algorithms"), ]), // other targets ] )