结构体和类都符合协议。我使用两个带有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'