[英]var defined in protocol doesn't conform to multiple protocol
I'm struggling with protocols in Swift.我正在为 Swift 中的协议苦苦挣扎。 I have defined a protocol like this:
我定义了一个这样的协议:
protocol AProtocol {
var property : BProtocol {get set}
}
And I would like to conform to AProtocol
in a class with a property that also conform to another protocol .我想在一个类中符合
AProtocol
,其属性也符合另一个协议。 I've tried in these two ways:我试过这两种方式:
class AClass: AProtocol {
var property = BClass()
}
and:和:
class AClass: AProtocol {
var property: BProtocol & MyBClassType = BProtocol()
}
but none of them seems to work (BClass itself confirm to BProtocol) This issue is a bit difficult to explain, I hope it was clear.但它们似乎都不起作用(BClass 本身向 BProtocol 确认)这个问题有点难以解释,我希望它很清楚。
Is it a limitation of the Swift language?这是 Swift 语言的限制吗? Do you know a work around to this?
你知道解决这个问题吗?
You have two issues: firstly, the property name must match that declared in the protocol, secondly you need to type annotate the variable to be of type BProtocol
as Hamish explained in the comment.您有两个问题:首先,属性名称必须与协议中声明的名称匹配,其次,您需要将变量类型注释为
BProtocol
类型,如 Hamish 在评论中解释的那样。
protocol AProtocol {
var aProperty : BProtocol {get set}
}
protocol BProtocol {}
class BClass: BProtocol {}
class AClass: AProtocol {
var aProperty: BProtocol = BClass()
}
You should also conform to the Swift naming convention, which is lowerCamelCase for variable names, so I changed AProperty
to its correct form, aProperty
.您还应该遵守 Swift 命名约定,即变量名称的
AProperty
,因此我将AProperty
更改为正确的形式aProperty
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.