为什么下面的协议有这个必需的功能?

为什么下面的协议有这个必需的功能?

问题描述:

WWDC 2015 上提到了以下代码:

The following code was mentioned at WWDC 2015:

protocol Drawable {
  func isEqualTo(other: Drawable) -> Bool
  func draw()
}

extension Drawable where Self : Equatable {
  func isEqualTo(other: Drawable) -> Bool {
    if let o = other as? Self { return self == o }
    return false
  } 
}

我对整个协议扩展这件事有点困惑.为什么他们会有 isEqualTo(other: Drawable) ->Drawable 协议中的 Bool 然后只在 self 是 equatable 时扩展?为什么 isEqualTo 应该是所有 Drawable 对象的必需方法?在我看来,如果一个新的类/结构没有实现 Equatable,对象就没有能力在逻辑上检查相等性,所以它们不能实现一个等价的方法.我认为让它成为一个可选的实现会更有意义.我的逻辑错在哪里?

I'm a little confused on this whole protocol extension thing. Why would they have isEqualTo(other: Drawable) -> Bool in the Drawable protocol and then only extend when self is equatable? Why should isEqualTo be a required method for all Drawable objects? From my view, if a new class/struct hasn't implemented Equatable, the objects don't have the capability to be logically checked for equality, so they couldn't implement an equatable method. I think it would make more sense to have it be an optional implementation. Where is the fault in my logic?

要解决的问题是泛型的局限性.

The problem being solved is a limitation of generics.

假设我们有一个 Bird 结构和 Insect 结构.通用等式允许我们定义 == ,其中实际的对象类型是相同的类型.所以我们可以让Bird采用Equatable,这样如果我们将b1b2都输入为Bird,我们就可以决定它们是否相等.我们可以让 Insect 采用 Equatable,这样如果我们将 i1i2 都输入为 Insect,我们就可以决定它们是否相等.

Let's say we have a Bird struct and Insect struct. A generic equatable lets us define == where the actual object types are the same type. So we can make Bird adopt Equatable so that if we have b1 and b2 both typed as Bird we can decide whether they are equal. And we can make Insect adopt Equatable so that if we have i1 and i2 both typed as Insect we can decide whether they are equal.

但现在假设 Bird 和 Insect 都采用 Flier 协议.你不能让 Flier 采用 Equatable,因为泛型的工作方式是有限制的.因此,如果两个对象的类型都为 Flier,则您无法为它们实现相等性.

But now suppose both Bird and Insect adopt the Flier protocol. You cannot make Flier adopt Equatable, because there's a limitation in how generics work. So if two objects are typed as Flier, you have no way of implementing equatability for them.

该视频演示了协议扩展解决了这个问题.使用 Flier 上的协议扩展,您可以定义一个 不同 方法来比较两个 Flier 并确定它们是否相等 - 即,首先确定它们是否属于同一类,然后应用 ==.因此,您可以理解 Flier(协议)的等价性.

The video demonstrates that protocol extensions solve this problem. With a protocol extension on Flier, you can define a different method that compares two Fliers and decides whether they are equal - namely, by deciding first whether they are of the same class and then applying ==. Thus you can make sense of equatability for a Flier (a protocol).