Swift-将默认比较功能作为功能参数进行引用

我正在尝试实现便捷的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,<)

我希望它默认为<,但是如何在函数签名中默认引用<运算符?

poiplkj 回答:Swift-将默认比较功能作为功能参数进行引用

在将未使用的<函数用作默认参数时,实际上可以通过将其包装在括号(<)中来引用它。

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])
    }
}

但是,执行此操作时,编译器当前存在问题。 即使没有<抛出,编译器仍会强制您在调用站点上使用try

有关此问题的错误报告已在很早之前打开,但仍未解决。如果您遇到此问题,请对其进行投票:https://bugs.swift.org/browse/SR-1534

此外,如注释中所指出,sorted(by:)函数实际上是2个不同的函数。

一个要求Comparable并在内部使用<,而另一个要求您直接指定排序逻辑,因此不需要Comparable一致性。

因此,通过keyPath进行的这种方便排序仍然需要2个功能。

本文链接:https://www.f2er.com/2612791.html

大家都在问