【问题标题】:Class does not conform to protocol, but struct does类不符合协议,但结构符合
【发布时间】:2019-08-28 09:48:03
【问题描述】:
结构和类都符合协议。我使用 2 个带有 where 条件的协议扩展来为类和结构添加 var 属性的实现。
我很惊讶只看到类的编译错误。
为什么这种情况发生在类而不是结构上?
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'
【问题讨论】:
标签:
swift
swift-protocols
【解决方案1】:
它不能编译,因为你的
extension MyProtocol where Self == MyClass
仅为MyClass 本身提供默认方法,而不为可能的子类提供默认方法。将约束更改为
extension MyProtocol where Self: MyClass
使代码编译。 或者阻止创建子类
final class MyClass : MyProtocol {}
这对MyStruct 来说不是问题,因为在 Swift 中无法继承结构类型。
【解决方案2】:
类可以从其他类继承。
所以某些类X 可能继承自MyClass。
但是您的扩展提供了 MyProtocol 属性的实现,如果该类是 MyClass 而不是它的后代。所以任何继承自MyClass 的类都不会实现MyProtocol 的任何属性。这就是问题所在。
如果您声明 MyClass final 您的代码将是有效的:
final class MyClass : MyProtocol {}
如果您将条件扩展扩展到任何 MyClass 后代,您的代码将是有效的:
extension MyProtocol where Self: MyClass {
var property: String { return "" }
}
但是现在所有这些潜在的子类都缺少MyProtocol 的实现,而且是不允许的。