简体   繁体   English

Swift 协议一致性

[英]Swift protocol conformity

I want a variable that conforms to protocol, but the swift compiler tells me the protocol does not confirm.我想要一个符合协议的变量,但是 swift 编译器告诉我协议没有确认。

protocol A {}
protocol B {
    var a : A { get }
}
class AA : A {}
// Type 'BB' does not conform to protocol 'B'
class BB : B { 
    let a = AA()
}

You are not conforming to the protocol because your a is not clearly typed as an A , but rather inferred as an AA .您不符合协议,因为您的a没有明确键入为A ,而是推断为AA Make it explicit.让它明确。

protocol A {}
protocol B {
    var a : A { get }
}
class AA : A {}

class BB : B {
    let a: A = AA() // Explicitly typed here.
}

The fact that you have used var in the protocol and let in the implementation is a red herring, as the var is a get only, and has no set .您在协议中使用了var并在实现中使用了let的事实是一个红鲱鱼,因为 var 只是一个get ,没有set

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM