Weekly Swift articles, podcasts and tips by John Sundell.

Generic algorithms

Published on 26 Mar 2019
Basics article available: Generics

A big benefit of Swift’s protocol-oriented design is that it makes it much easier to implement generic algorithms that can be used in many different contexts. For example, here we’re not only extending Array - we’re extending all RandomAccessCollection types:

extension RandomAccessCollection {
    func element(at index: Index) -> Element? {
        guard indices.contains(index) else {
            return nil
        }

        return self[index]
    }
}

By implementing extensions on standard library protocols instead of concrete types, our added functionality can be used in so many more contexts. For example, the above extension can now be used not only on Array, but also on Data, many kinds of ranges, IndexPath, KeyValuePairs, and many more.