A protocol can inherit from another protocol, like a class can inherit from another class. Protocols can even inherit from multiple protocols at the same time!
A struct, class, or enum that conforms to a protocol must implement all requirements from the protocol as well as any of the protocols that it inherits from.
protocol Viewer { func login() func logout() func showContent() } protocol Creator: Viewer { func uploadNewContent(name: String) } struct VideoContentCreator: Creator { func login() { print("Successfully logged in") } func logout() { print("Successfully logged out") } func showContent() { print("Here are the new videos") } func uploadNewContent(name: String) { print("Thanks for uploading your new video: \(name)!") } }
In the example above, we have a protocol Viewer
that has three functions. The protocol Creator
inherits Viewer
and adds another function of its own. Since the VideoContentCreator
struct conforms to the Creator
protocol, it has to implement all the functions laid down in Viewer
and Creator
.
Instructions
Take a look at the code in the editor. To conform to the CustomStringConvertible
protocol, a struct just needs to add a description
property of type String
. Also note that the Car
s array:
let cars: [Car] = [modelX, achieva]
Car
is a protocol, which means that the array can hold any struct, class, or enum that conforms to Car
. When accessing elements in cars
, we are only allowed to use properties and methods that have been defined in the Car
protocol.
The code here is missing some protocol conformance to compile! Click “Run” to continue and let’s fix it.
Make GasCar
and ElectricCar
inherit from the appropriate protocol so that the code compiles.