首页 > 解决方案 > 协议扩展使用 where 子句在 Swift 中不起作用

问题描述

我们知道在 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的数组执行 binarySearch 。Comparable

但是上面的代码在编译的时候是错误的。那么如何解决呢?谢谢 ;)

标签: swiftwhere-clauseswift-protocols

解决方案


Adding :

extension Int: Ordered { }

will fix the compiler error but Ordered is redundant with Comparable. Why not just declaring :

func binarySearch<T: Comparable>(sortedKeys: [T], forKey k: T) -> Int { 11 }

?


推荐阅读