In Swift declare protocol variable that has to conform to at least one protocol

572 Views Asked by At

How can I define a variable in a protocol in Swift4 that at least needs to conform to a protocol, but can also conform to other protocols as well?

For example I now get an error if the protocol declares that a variable should conform to protocol B and I want the variable in the implementation to conform to a composite of different protocols (B + C).

 // For example: Presenter can conform to default stuff
    protocol A {
        var viewController: C? { get set }
        func presentDefaultStuff()
    }

    extension protocol A {
       func presentDefaultStuff() {
            viewController?.displayDefaultStuff()
       }

    // Presenter can conform to custom stuff
    protocol B {
       func presentCustomStuff()
    }

    // viewController can conform to default stuff
    protocol C {
        func displayDefaultStuff()
    }

   // viewController can conform to custom stuff
    protocol D {
        func displayCustomStuff()
    }

    class SomeClass: A & B {
        // Gives an error: Type 'SomeClass' does not conform to protocol 'A'
        // because protocol A defines that viewController needs to be of    
        // type C?
        var viewController: (C & D)?
    }

Edited: I edited my original post to make the question more clear I also found a solution to do the thing that I wanted to achieve: I can split the class and make an extension on the implementation that conforms to one of the protocols like this:

class someClass: B {
    customViewController: (C & D)?
}

extension someClass: A {
    var viewController: C? {
       return customViewController
    }
}

The compiler does a type check that customViewController conforms to C?.

0

There are 0 best solutions below