【问题标题】:protocol extension use where clause doesn't work in Swift协议扩展使用 where 子句在 Swift 中不起作用
【发布时间】: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) -&gt; Bool { self &lt; other } }

标签: swift where-clause swift-protocols


【解决方案1】:

添加:

extension Int: Ordered { }

将修复编译器错误,但 OrderedComparable 是多余的。为什么不直接声明:

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

?

【讨论】:

  • 请参考以下文章:wwdcnotes.com/notes/wwdc15/408,在“追溯适配”部分
  • 如果你想在Int的数组上使用binarySearch&lt;T: Ordered&gt;(sortedKeys:),你是否意识到Int仍然需要符合Ordered
  • Global function 'binarySearch(sortedKeys:forKey:)' requires that 'Int' conform to 'Ordered' 实际上这正是编译器告诉你的,这是我回答的第一部分
  • 请参考Type Constraints
猜你喜欢
  • 1970-01-01
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
  • 2018-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多