Mastering macOS Programming
上QQ阅读APP看书,第一时间看更新

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.