Articles, podcasts and news about Swift development, by John Sundell.

Passing operators as functions

Published on 29 Jul 2019

One of my favorite things about Swift is just how so many of its language features that are implemented using its own type system. Take operators for example — they’re functions — which means that we can pass them, and call them, as functions/closures!

enum SortOrder {
    case ascending
    case descending
}

internal extension SortOrder {
    func makeComparator<T: Comparable>() -> (T, T) -> Bool {
        switch self {
        case .ascending:
            // Since Swift operators are implemented as
            // functions, we can both pass them as closures...
            return (<)
        case .descending:
            return (>)
        }
    }
}

internal extension Array {
    mutating func sort<T: Comparable>(by keyPath: KeyPath<Element, T>,
                                      order: SortOrder = .ascending) {
        sort { a, b in
            // ...and call them as closures!
            order.makeComparator()(
                a[keyPath: keyPath],
                b[keyPath: keyPath]
            )
        }
    }
}

Support Swift by Sundell by checking out this sponsor:

Essential Developer

Essential Developer: Learn the most up-to-date techniques and strategies for testing new and legacy Swift code in this free practical course for developers who want to become complete senior iOS developers. This virtual event includes lectures, mentoring sessions, and step-by-step instructions. Click to learn more.