Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a protocol conform to another protocol

I have two protocols: Pen and InstrumentForProfessional. I'd like to make any Pen to be an InstrumentForProfessional:

protocol Pen {   var title: String {get}   var color: UIColor {get} }  protocol Watch {} // Also Instrument for professional protocol Tiger {} // Not an instrument  protocol InstrumentForProfessional {   var title: String {get} }  class ApplePen: Pen {   var title: String = "CodePen"   var color: UIColor = .blue }  extension Pen: InstrumentForProfessional {} // Unable to make ApplePen an Instument for Professional: Extension of protocol Pen cannot have an inheritance clause  let pen = ApplePen() as InstrumentForProfessional 
like image 541
Richard Topchii Avatar asked Jun 21 '18 10:06

Richard Topchii


People also ask

Can a protocol conform to another protocol?

One protocol can inherit from another in a process known as protocol inheritance. Unlike with classes, you can inherit from multiple protocols at the same time before you add your own customizations on top. Now we can make new types conform to that single protocol rather than each of the three individual ones.

Can a protocol extend a protocol Swift?

In Swift, you can even extend a protocol to provide implementations of its requirements or add additional functionality that conforming types can take advantage of. For more details, see Protocol Extensions. Extensions can add new functionality to a type, but they can't override existing functionality.

How many protocols can a Swift class adopt?

Swift 4 allows multiple protocols to be called at once with the help of protocol composition.

What is protocol composition and protocol extension?

Protocol composition is the process of combining multiple protocols into a single protocol. You can think of it as multiple inheritance. With protocol DoSomething , below, class HasSomethingToDo is able to do whatShouldBeDone and anotherThingToBeDone .


1 Answers

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.

like image 87
user28434'mstep Avatar answered Sep 28 '22 03:09

user28434'mstep