Class 不符合协议,但结构符合

Class does not conform to protocol, but struct does

结构和class都符合协议。我使用 2 个带有 where 条件的协议扩展来为 class 和 struct.

添加 var 属性 的实现

我很惊讶地看到只有 classes 的编译错误。

为什么 classes 而不是结构会发生这种情况?

protocol MyProtocol {
    var property:String { get }
}

extension MyProtocol where Self == MyStruct {
    var property: String { return "" }
}

extension MyProtocol where Self == MyClass {
    var property: String { return "" }
}

struct MyStruct : MyProtocol {}

class MyClass : MyProtocol {} //Type 'MyClass' does not conform to protocol 'MyProtocol'

它无法编译因为你的

extension MyProtocol where Self == MyClass

仅为 MyClass 本身提供默认方法,但不为可能的子类提供默认方法。将约束更改为

extension MyProtocol where Self: MyClass

编译代码。 或者 防止创建子类

final class MyClass : MyProtocol {}

这对 MyStruct 来说不是问题,因为无法从 Swift.

中继承结构类型

类 可以继承其他 classes。

所以有些 class X 可能继承自 MyClass.

但是如果 class 是 MyClass 而不是它的后代,则您的扩展提供了 MyProtocol 属性的实现。因此,任何继承自 MyClass 的 class 都不会实现 MyProtocol 的任何属性。这就是问题所在。

如果您声明 MyClass final 您的代码将有效:

final class MyClass : MyProtocol {}

如果您将条件扩展扩展到任何 MyClass 个后代,您的代码将有效:

extension MyProtocol where Self: MyClass {
    var property: String { return "" }
}

但是现在所有这些潜在的子classes 都没有实现 MyProtocol,这是不允许的。