In this example, I see that a Struct is using protocol inheritance.
This is not protocol inheritance. This is the FlyingCar
struct adopting or conforming to the CanFly
and CanDrive
protocols.
To quote from the language guide:
A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.
So classes, structs and enums do not inherit from a protocol, they adopt it and implement the blueprint laid out by the protocol.
However, it needs to add in the 'vars' from the previous protocols CanFly and CanDrive so the code can work. I have tested this in Playground.
Why?
Because any struct, class or enumeration that conforms to a protocol has to implement the required properties and methods of that protocol. Since you state that FlyingCar
conforms to CanFly
and CanDrive
, it has to implement the required properties of those protocols.
This is from the lesson on Protocol Inheritance. It seems 'protocol Employee' is inheriting from Payable, NeedsTraining, and HasVacation, but clearly is not elaborating upon any of the func found in any of those parent protocols. It's simply empty { }.
Protocols, on the other hand, can inherit from other protocols. Using your example, the Employee
protocol inherits the methods defined in the Payable
, NeedsTraining
, and HasVacation
protocols but any struct, class or enum that adopts the Employee
protocol will have to implement those methods.
Protocol inheritance is basically just a shorthand way of grouping protocols that are frequently used together. Or it can provide a way to compose protocols from smaller pieces.
You could do this:
struct Drone: Payable, NeedsTraining, HasVacation {
//and implement the required properties and methods
}
Or you can use protocol inheritance to create the Employee
protocol and do this:
struct Drone: Employee
//and implement the required properties and methods
}
Same end result.
To throw a further wrench into things, protocols can have default implementations. But I'll leave that for a future discovery.
I highly recommend reading the language guide page on protocols.