Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to create a default implementation for 2 protocol implementations?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// 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

>Solution :

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
     }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading