Articles and podcasts about Swift development, by John Sundell.

Genius Scan SDK

Presented by the Genius Scan SDK

This article has been archived, as it was published several years ago, so some of its information might now be outdated. For more recent articles, please visit the main article feed.

Generic algorithms

Published on 26 Mar 2019
Discover page 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.

Genius Scan SDK

Swift by Sundell is brought to you by the Genius Scan SDK — Add a powerful document scanner to any mobile app, and turn scans into high-quality PDFs with one line of code. Try it today.