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:

Emerge

Emerge: Continuously monitor and reduce your app’s size. Emerge’s easy to use plugins for GitHub and fastlane will automatically scan your app’s binary and provide you with simple, actionable suggestions on how to make it smaller and, in turn, faster for your users to download. Set up a demo now!