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:
- A protocol which defines the responsibilities that will be delegated
- The delegator, which delegates the responsibilities conforming to the protocol
- The delegate, which adopts the protocol and implements its requirements
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.