Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift protocol inheritance [duplicate]

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?

like image 605
somedev Avatar asked Aug 12 '16 14:08

somedev


Video Answer


1 Answers

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 }
}
like image 61
somedev Avatar answered Oct 15 '22 21:10

somedev