Algorithms
Swift Algorithms is an open-source package of sequence and collection algorithms, along with their related types.
import Algorithms
Module information
- Declarations
- 366
- Symbols
- 3883
Overview
The Algorithms package provides a variety of sequence and collection operations, letting you cycle over a collection’s elements, find combinations and permutations, create a random sample, and more.
For example, the package includes a group of “chunking” methods, each of which breaks a collection into consecutive subsequences. One version tests adjacent elements to find the breaking point between chunks — you can use it to quickly separate an array into ascending runs:
let numbers = [10, 20, 30, 10, 40, 40, 10, 20]
let chunks = numbers.chunked(by: { $0 <= $1 })
// [[10, 20, 30], [10, 40, 40], [10, 20]]
Another version looks for a change in the transformation of each successive value. You can use that to separate a list of names into groups by the first character:
let names = ["Cassie", "Chloe", "Jasmine", "Jordan", "Taylor"]
let chunks = names.chunked(on: \.first)
// [["Cassie", "Chloe"], ["Jasmine", "Jordan"], ["Taylor"]]
Explore more chunking methods and the remainder of the Algorithms package, grouped in the following topics.
Topics
Combinations and Permutations
Find the combinations and permutations of any collection’s elements, or the product of two different collections.
Read MoreSlicing and Splitting
Iterate over tuple pairs of adjacent elements, overlapping windows of a specified size, or lazily-calculated splits.
Read MoreChunking
Break collections into consecutive chunks by length, count, or based on closure-based logic.
Read MoreJoining
Join the parts of a collection of collections, providing a connecting element or collection, or a closure that produces the connector.
Read MoreExtending
Chain two collections end-to-end, or repeat a collection forever or a specific number of times.
Read MoreTrimming
Remove unwanted elements from the start, the end, or both ends of a collection.
Read MoreKeying and Grouping
Convert a sequence to a dictionary, providing keys to individual elements or to use as grouping values.
Read MoreRandom Sampling
Choose a specified number of random elements from a sequence or collection.
Read MoreFinding the Minimum and Maximum
Find the minimum and maximum elements simultaneously, or a specific number of elements at the minimum and maximum.
Read MoreSelecting Elements
Select elements at a particular interval, the first mapped value, or iterate of elements with their indices.
Read MoreFiltering
Remove duplicated elements or strip the
Read Morenil
values from a sequence or collection.Reductions
Find the incremental values of a sequence “reduce” operation.
Read MorePartitioning and Rotating
Partition a collection according to a unary predicate, rotate a collection around a particular index, or find the index where a collection is already partitioned.
Read More