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
Curl Through Nstask Not Terminating If a Pipe Is Present
How to Convert PDF to Png Efficiently
In Swift, Can You Split a String by Another String, Not Just a Character
Contextual Type for Closure Argument List Expects 1 Argument, But 4 Were Specified
Create Nsmanagedobject Subclass... Make a New Error in My Project
iOS Facebook Sdk: Login Doesn't Return Email Despite Permissions Granted
Swift 4 Decode Simple Root Level JSON Value
Swiftui List Empty State View/Modifier
Can't Hook Up an Outlet Collection in Xcode 6 Using Storyboard
Constant Speed Orbit Around Point with Sknode
Swift, Auto Resize Custom Table View Cells
Make Property of Type and Also Conform to Protocol in Swift
Best Practice for Swift Methods That Can Return or Error
Back Button Image - What Is It Called in Swift
Get Image from Calayer or Nsview (Swift 3)
How to Import a Swift Function Declared in a Compiled .Swiftmodule into Another Swift File