我正在尝试实现便捷的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,<)
我希望它默认为<
,但是如何在函数签名中默认引用<
运算符?