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.
Passing operators as functions
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]
)
}
}
}

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.