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!
                a[keyPath: keyPath],
                b[keyPath: keyPath]