Swift 5.2 makes it so you can use the same extension for key paths and closures.
func sorted<Comparable: Swift.Comparable>(
_ getComparable: (Element) throws -> Comparable,
_ getAreInIncreasingOrder: (Comparable, Comparable) throws -> Bool = (<)
) rethrows -> [Element] {
try sorted {
try getAreInIncreasingOrder( getComparable($0), getComparable($1) )
}
}
The problem with this method is that, even though <
doesn't throw, the compiler will still enforce you to use try
at the call site.
I don't know if that's worthy of a bug report.
As it is, two overloads are the way to go.
func sorted<Comparable: Swift.Comparable>(
_ getComparable: (Element) throws -> Comparable
) rethrows -> [Element] {
try sorted(getComparable, <)
}
func sorted<Comparable: Swift.Comparable>(
_ getComparable: (Element) throws -> Comparable,
_ getAreInIncreasingOrder: (Comparable, Comparable) throws -> Bool
) rethrows -> [Element] {
try sorted {
try getAreInIncreasingOrder( getComparable($0), getComparable($1) )
}
}