executor21
executor21

Reputation: 4596

In Swift, why isn't protocol conformance detected when one protocol is used inside another?

So I have a protocol, and one of its fields is an instance of another protocol.

protocol Inner {
    var x: Int { get }
}

protocol Outer {
    var y: Inner { get }
}

Then I have classes that should conform to the respective protocols:

class InnerImpl {
    var x: Int = 0
}

class OuterImpl {
    var y = InnerImpl()
}

Except I can't just declare conformance:

extension InnerImpl: Inner {} //this is fine

extension OuterImpl: Outer {} //compiler error: Type 'OuterImpl' does not conform to the protocol 'Outer'

Why doesn't this work? It doesn't even work if I declare conformance of InnerImpl to Inner in the class declaration rather than an extension.

The conformance declarations work if I set the field to the protocol rather than the concrete class in the implementation:

var y: Inner = InnerImpl()

Why does that make a difference and what would I accomplish what I need here with a class I can't modify?

Upvotes: -1

Views: 21

Answers (0)

Related Questions