协议中定义的 var 不符合多协议

var defined in protocol doesn't conform to multiple protocol

我正在努力处理 Swift 中的协议。 我定义了这样的协议:

protocol AProtocol {
    var property : BProtocol {get set}
}

而且我想在 class 中遵守 AProtocol 和 属性 也遵守另一个协议 。我试过这两种方式:

class AClass: AProtocol {
   var property = BClass()
}

和:

class AClass: AProtocol {
   var property: BProtocol & MyBClassType = BProtocol()
}

但其中 none 似乎有效(BClass 本身确认 BProtocol) 这个问题有点难解释,希望大家明白。

这是Swift语言的限制吗? 你知道解决这个问题的方法吗?

您有两个问题:首先,属性 名称必须与协议中声明的名称相匹配,其次,您需要将变量类型注释为 BProtocol 类型,正如 Hamish 在评论中所解释的那样.

protocol AProtocol {
    var aProperty : BProtocol {get set}
}

protocol BProtocol {}
class BClass: BProtocol {}

class AClass: AProtocol {
    var aProperty: BProtocol = BClass()
}

你还应该遵守 Swift 命名约定,变量名是 lowerCamelCase,所以我将 AProperty 更改为正确的形式,aProperty.