Home > Software design >  Is it possible to create a default implementation for 2 protocol implementations?
Is it possible to create a default implementation for 2 protocol implementations?

Time:08-24

I want to know if it is possible to create a default implementation for 2 protocols implementations at the same time.

For example

protocol Coordinator { 
    var navigationController: UINavigationController
}
protocol Browsing { 
    func openBrowser(url: String)
}

And be able to create a default implementation like so

// This syntax is not correct of course, it is just an example
extension (Coordinator & Browsing) {
     func openBrowser() { 
          //code
          navigationController.present(...)
     }
}

I want to be able to do this, because I'll have multiple classes extending both protocols

CodePudding user response:

You can use the where clause on an extension to require a type conforming to multiple protocols.

Either of these will work and do the same thing. It's up to you which one makes sense. I'd probably go with the second one since the method came from Browsing and this adds the implementation when it also conforms to Coordinator.

extension Coordinator where Self: Browsing {
     func openBrowser() { 
          //code
     }
}
extension Browsing where Self: Coordinator {
     func openBrowser() { 
          //code
     }
}
  • Related