【发布时间】:2021-05-16 14:05:51
【问题描述】:
我们知道在 Swift 中,我们可以在协议扩展中使用where 子句:
protocol Ordered {
func precedes(other: Self) -> Bool
}
func binarySearch<T: Ordered>(sortedKeys: [T], forKey k: T) -> Int { 11 }
// I want make all Comparable types confirm Ordered protocol,but compiler complained later...
extension Ordered where Self: Comparable {
func precedes(other: Self) -> Bool {
return self < other
}
}
// ERROR: Global function 'binarySearch(sortedKeys:forKey:)' requires that 'Int' conform to 'Ordered'
let position = binarySearch(sortedKeys: [2, 3, 5, 7], forKey: 5)
因为Int、String、Double等都符合Comparable,所以我想对任意Comparable类型的数组执行binarySearch。
但是上面的代码在编译的时候是错误的。那么如何解决呢? 谢谢;)
【问题讨论】:
-
只是扩展 Comparable 协议而不是
extension Comparable {func precedes(_ other: Self) -> Bool { self < other }}
标签: swift where-clause swift-protocols