4

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 Answer 1

3

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 {} 
Sign up to request clarification or add additional context in comments.

2 Comments

Well, now I get "ProtocolA can only be used as a generic constraint because it has Self or associated type requirements" when I try to use it as: let array = Array<ProtocolA> What I forgot to say is that while the protocols are Public, the classes are Private (now edited) and I don't want to expose the internal classes.
How to do it if you can't modify ProtocolA ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.