类不符合协议,但struct符合

动脉瘤

结构和类均符合协议。我使用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'
马丁·R

它不会编译,因为

extension MyProtocol where Self == MyClass

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

extension MyProtocol where Self: MyClass

使代码编译。或者阻止使用以下方法创建子类

final class MyClass : MyProtocol {}

这不是问题,MyStruct因为无法在Swift中继承结构类型。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章