结构和类均符合协议。我使用2个协议扩展,并为where
条件添加了class和struct的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'
它不会编译,因为
extension MyProtocol where Self == MyClass
仅为MyClass
其自身提供默认方法,但不为可能的子类提供默认方法。将约束更改为
extension MyProtocol where Self: MyClass
使代码编译。或者阻止使用以下方法创建子类
final class MyClass : MyProtocol {}
这不是问题,MyStruct
因为无法在Swift中继承结构类型。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句