Articles, podcasts and news about Swift development, 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.

Support Swift by Sundell by checking out this sponsor:

Raycast

Raycast: Take the macOS Spotlight experience to the next level: Create Jira issues, manage GitHub pull requests and control other tools with a few keystrokes. Easily automate every-day tasks and boost your developer productivity by downloading Raycast for free.