As Apple tells:

A delegate is an object that acts on behalf of, or in coordination with, another object when that object encounters an event in a program.

Delegation is used when an entity (a class) assigns (delegates) responsibility or authority to another entity.

In Swift, there are three actors involved in delegation:

  1. A protocol which defines the responsibilities that will be delegated
  2. The delegator, which delegates the responsibilities conforming to the protocol
  3. The delegate, which adopts the protocol and implements its requirements

swift-delegation-patern

In the following few lines we are going to write a simple example that you can run in a playground. The example is very simple, a delegator will delegate the computation of a math work to a delegate using a protocol.

First of all we are going to define the protocol:

Then the delegate

And last the delegator

Using the playground you can try the above code issuing the following lines.

the last line will produce the output “1”, you can try with different values to verify the delegation is working.

Gg1