9

I have swift code:

protocol ParentProtocol {
    // stuff
}

protocol ChildProtocol: ParentProtocol {
    // additional stuff
}

protocol FooProtocol {
    var variable: ParentProtocol? { get }
}

class Foo:FooProtocol {
    var variable: ChildProtocol?
}

I've got compiler error:

Type 'Foo' does not conform to protocol 'FooProtocol'

I know, that according to the FooProtocol, variable type must be ParentProtocol type. On the other hand ChildProtocol inherits from ParentProtocol, so it also is a ParentProtocol

Is there any solution to use protocol inheritance in that way?

Lukas Würzburger
  • 6,543
  • 7
  • 41
  • 75
somedev
  • 791
  • 11
  • 29
  • @ShadowOf yep, thanks. Solution with associated types works as expected: http://stackoverflow.com/a/38008288/824285 – somedev Aug 12 '16 at 14:29
  • Related: [How can I make a function with a Subclass return type conform to a protocol, where a Superclass is defined as a return type?](http://stackoverflow.com/questions/35094967/swift-how-can-i-make-a-function-with-a-subclass-return-type-conform-to-a-protoc) – Hamish Aug 12 '16 at 14:30
  • 1
    Also related (conformance and inheritance of metatypes): [Protocol doesn't conform to itself?](http://stackoverflow.com/questions/33112559/protocol-doesnt-conform-to-itself), quoting MartinR:s comment, _"Even with `protocol P : Q { }`, `P` does not conform to `Q`"_. – dfrib Aug 12 '16 at 14:37

1 Answers1

7

I found the solution with associated types (https://stackoverflow.com/a/38008288/824285)

In my case it would be:

protocol FooProtocol {
   associatedtype T = ParentProtocol
   var variable:T? { get }
}
Community
  • 1
  • 1
somedev
  • 791
  • 11
  • 29
  • 3
    Note that in class that conform this protocol `T` can become any type in fact, not only `ParentProtocol` or it child, `String` for example. – Yury Aug 12 '16 at 14:39