Swift protocol property in protocol - Candidate ha

2019-06-24 14:51发布

I have a protocol (ProtocolA) containing a single property conforming to a second protocol (ProtocolB).

public protocol ProtocolA {        
    var prop: ProtocolB? { get }
}

public protocol ProtocolB {        
}

I'm trying to declare two classes that will implement those:

private class ClassA : ProtocolA {    
    var prop: ClassB?
}

private class ClassB : ProtocolB {
}

But I get an error:

Type 'ClassA' does not conform to protocol 'ProtocolA'

Protocol requires property 'prop' with type 'ProtocolB?'

Candidate has non-matching type 'ClassB?'

Which is annoying as ClassB conforms to ProtocolB.

in the good-old i'd probably just declare the property as:

@property (nonatomic) ClassB <ProtocolB> *prop;

but the only way it seems I can get around this in swift is by adding an ivar like:

private class ClassA : ProtocolA {        
    var _prop: ClassB?
    var prop: ProtocolB? { return _prop }
}

Is there no way around this?

1条回答
Lonely孤独者°
2楼-- · 2019-06-24 15:33

You need to declare a typealias of the type that conforms to the other protocol. The way you did it is that prop has to be exactly of type ProtocolB, but you don't actually want that, you want a type that conforms to it instead.

protocol ProtocolA {
    typealias Prop : ProtocolB
    var prop: Prop? { get }
}

protocol ProtocolB {}


class ClassA : ProtocolA {
    var prop: ClassB?
}

class ClassB : ProtocolB {}
查看更多
登录 后发表回答