Protocols
A protocol is a guarantee made by any type that conforms to (or adopts) that protocol, that it will comply with certain requests when required to do so.
If we have a Tractor
type, a Helicopter
type, and a Submarine
type, we may wish that they all implement a takeMeToTheBeach
method. We don't care how they do it, each type will take care of the details itself, in possibly very different ways (depending on who's flying the submarine), but we do know that they will implement a method of that name.
Declaring protocols involves specifying either or both the following:
- Methods that conformant types must implement
- Properties that conformant types must implement
Once we have types that conform to protocols, we can often dispense with the need for subclassing abstract classes.
Declaring method requirements
Let us start by declaring a simple protocol and having a look at what it all means:
protocol Talkative { func sayHi() }
The Talkative
protocol says that any type declaring itself to conform...