Introducing Swift Algorithms

Swift Algorithms, "a new open-source package of sequence and collection algorithms, along with their related types", is now available:

Please feel free to use this thread to ask questions!

CC @nnnnnnnn @kylemacomber


Fantastic! Advent of Code just got 50% easier in Swift and I can replace all of my implementations of similar algorithms. (My apps will also benefit. :smile:) Now where's that Swift Collections library... :thinking:


This is great!

Some of the algorithms here accept a subrange parameter. For example:

var numbers = [10, 20, 30, 40, 50, 60]
numbers.rotate(subrange: 0..<3, at: 1)

As I understand it, the goal of Swift is to allow that to be written as

var numbers = [10, 20, 30, 40, 50, 60]
numbers[0..<3].rotate(at: 1)

The readme on the Rotate methods calls this out:

To work around the CoW / slice mutation problem for divide-and-conquer algorithms, which are the idiomatic use case for rotation, this also includes variants that take a range.

Is the introduction of subrange: parameters in these algorithms an admission that the slice mutation problem is unlikely to be fixed anytime soon?


I have a couple of algorithms laying around that could be useful here (longest sorted subsequence and extracting collection transform steps from one collection to another) but they work on indexes rather than the collections themselves.

Would that be something that this package would still want?

Thanks, all!

These are included to support people who are writing generic collection algorithms today. They aren't intended to be a long-term decision about the slice mutation issue.

Indexes are an intrinsic part of collections, so algorithms that deal in indexes make perfect sense.

Great job guys, super useful thank you :rocket:

1 Like


Just as a suggestion the Swift Algorithm Club at the Wenderlich site has a long list of more than 80 Swift algorithms they've implemented. It could possibly serve as food for thought for desired and useful algorithms. I guess it only exists because there was no official swift algorithms library until now.

The Swift Algorithm Club is a tutorial series focused on teaching algorithms and data structures, and Swift in relation to those algorithm and data structures. That repository is a code repository for things covered in those tutorials. While some of that code is perfectly reasonable for general use, quite a lot of it is not suited for use outside of a learning context.

It would exist even if Swift had a Python style "batteries included" standard library.

Terms of Service

Privacy Policy

Cookie Policy