Swift Algorithms is a new package including a number of sequence and collection algorithms that are going to fill a gap in Swift standard library, writes Apple engineer Nat Cook.

The Algorithms package includes a host of powerful, generic algorithms frequently found in other popular programming languages. We hope this new package will help people embrace algorithms, improving the correctness and performance of their code.

As an example of similar libraries available for other languages, Cook mentions itertools for Python and the C++ algorithms library. Specifically, Swift Algorithms will include generic algorithms over the Sequence and Collection protocols, and will not include classic algorithms such as sort algorithms nor algorithms over non-linear data structures.

The importance of choosing the right algorithms and data structures cannot be overstated and the lack of a standard library supporting this has in some cases reduced the attention Swift developers pay to it, as Dave Abrahams noticed in the “Embrace Algorithms” talk he gave at WWDC 2018.

We think the Algorithms package can help realize this goal by serving as a low-friction venue to build out new families of related algorithms—giving us an opportunity to iteratively explore the problem space and learn how different algorithms connect and interact—before graduating them into the standard library.

Swift Algorithms is still in its early stages and the number of algorithms it includes is still quite reduced. Namely, Swift Algorithms includes a Combinations generic type that computes combinations of a collection’s elements; a Permutations generic type to compute permutations of a collection’s elements, or of a subset of those elements; a product function to iterating over every pair of elements in two different collections; a set of chunked methods to break a collection into subsequences; a chain method to concatenate two collections with the same element type; a set of cycle methods to iterate over a collection; a uniqued method to strip repeated elements from a sequence or collection; a set of randomSample methods to carry through operations for randomly selecting k elements from a sequence or collection; an indexed method, which pairs elements of two collections; partition methods to perform a stable partition on mutable collections, and for finding the partitioning index in an already partitioned collection; and a rotating method to rotate the elements of a collection to new positions.

#macos #ios #swift #system programming #development #news

The Swift Team Open-Sources Swift Algorithms
1.20 GEEK