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:
protocol MyDelegateProtocol { func computeproduct(x:Int, y:Int) }
Then the delegate
class MyDelegate: MyDelegateProtocol { func computeproduct(x:Int, y:Int) { print (x * y) } }
And last the delegator
class Delegator { var delegate: MyDelegateProtocol? func testDelegate(v1: Int, v2:Int) { delegate?.computeproduct(v1, y: v2) } }
Using the playground you can try the above code issuing the following lines.
var delegator = Delegator() var mydelegate = MyDelegate() delegator.delegate = mydelegate delegator.testDelegate(4, v2: 1)
the last line will produce the output “1”, you can try with different values to verify the delegation is working.
Gg1