Extend Existing Protocols to Implement Another Protocol with Default Implements

Make a protocol conform to another protocol

Protocols can inherit each other:

Protocol Inheritance


A protocol can inherit one or more other protocols and can add further requirements on top of the requirements it inherits. The syntax for protocol inheritance is similar to the syntax for class inheritance, but with the option to list multiple inherited protocols, separated by commas:

protocol InheritingProtocol: SomeProtocol, AnotherProtocol {
// protocol definition goes here
}

So, you basically need to do this:

protocol InstrumentForProfessional {
var title: String {get}
}

protocol Pen: InstrumentForProfessional {
var title: String {get} // You can even drop this requirement, because it's already required by `InstrumentForProfessional`
var color: UIColor {get}
}

Now everything that conforms to Pen conforms to InstrumentForProfessional too.

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

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 Topics



Leave a reply



Submit