我正在尝试实现便捷的Collection.sorted(by: KeyPath)
功能。
到目前为止,如果可以,就可以使用>
func sorted<T: Comparable>(by keyPath: KeyPath<Element, T>) -> [Element] { return sorted { lhs, rhs return lhs[keyPath: keyPath] < rhs[keyPath: keyPath] } }
但是如果我想允许调用者指定实际的排序逻辑怎么办?我添加了一个回调来执行比较,就像这样(从原始的
sorted(_:)
函数签名中获取灵感)。
func sorted<T: Comparable>(by keyPath: KeyPath<Element, T>, _ compare: (T, T) throws -> Bool) rethrows -> [Element] { return try sorted { lhs, rhs in return try compare(lhs[keyPath: keyPath], rhs[keyPath: keyPath]) } }
现在,这一切正常,但这意味着呼叫站点始终必须指定要执行的排序操作。
let sorted = myArray.sorted(by: \.name, <)
我希望它默认为<
,但是如何在我函数的签名中默认引用<
运算符?
我正在尝试实现便利的Collection.sorted(by:KeyPath)函数。到目前为止,如果func sorted
<
函数用作默认参数时将其包装在括号(<)
中来引用它。func sorted<T: Comparable>(
by keyPath: KeyPath<Element, T>,
_ compare: (T, T) throws -> Bool = (<)
) rethrows -> [Element] {
return try sorted { lhs, rhs in
return try compare(lhs[keyPath: keyPath], rhs[keyPath: keyPath])
}
}