简体   繁体   中英

var defined in protocol doesn't conform to multiple protocol

I'm struggling with protocols in 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 . 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.

Is it a limitation of the Swift language? 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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