Protocols: blueprints for how a piece of functionality should be implemented


protocol TheProtocolName {
  // definition

// adopted by a class
class myClass: Superclass, TheProtocol, OtherProtocol {
  // yadda, yadda, yadda

A protocol defines the properties and methods that a class, structure, or enumeration must implement to claim to conform to said protocol. The protocol specifies the name and type of a property to be supported, or the input and output types of a method to be supported, but none of the implementation details. Property requirements are also declared as variable, even if they are only gettable. Even though protocols do not implement any functionality, they can still be used as first class types in many places, such as parameters or output from a function, the type of a variable or constant, or the type held by an array or dictionary. This feature allows you to store objects of different types in the same array (provided they all implement the protocol), but the only functionality available on those objects is that which is defined by the protocol.

protocol TheProtocol {
  var mySettableAttribute: String { get set }
  var myReadAttribute: Int { get }
  func theFunction(Int, Int) -> Double