Delegate Pattern
2 min readMar 20, 2023
The name Delegate comes from the concept of delegating control (giving control to something else). In Swift, a delegate is a controller object with a defined interface that can be used to control or modify the behaviour of another object.
Generalised Example:
Your manager assigns you (developer) a particular task. You do the task and get its output. And then returns it back to the manager. This is a delegation pattern.
Ways to implement delegation pattern:
- Delegate pattern (with reference):
class Developer {
var managerReference: Manager?
func developWillAdd(a: Int, b: Int) {
managerReference?.didFinishedAdding(result: a+b)
}
}
class Manager {
var developer: Developer?
init(developer: Developer?) {
self.developer = developer
// To tell the compiler that output should be returned to this class
developer?.managerReference = self
}
func addTwoNumbers(num1: Int, num2: Int) {
developer?.developWillAdd(a: num1, b: num2)
}
func didFinishedAdding(result: Int) {
print(result)
}
}
let obj = Manager(developer: Developer())
obj.addTwoNumbers(num1: 10, num2: 20)
2. Delegate pattern (with protocol) :
protocol AdditionDelegate: AnyObject {
func didFinishedAdding(result: Int)
}
class Developer {
// Basically delegate
// delegate is initialized with weak keyword here in order to avoid any memory leaks
weak var managerReference: AdditionDelegate?
func developWillAdd(a: Int, b: Int) {
managerReference?.didFinishedAdding(result: a+b)
}
}
class Manager: AdditionDelegate {
var developer: Developer?
init(developer: Developer?) {
self.developer = developer
developer?.managerReference = self
}
func addTwoNumbers(num1: Int, num2: Int) {
developer?.developWillAdd(a: num1, b: num2)
}
func didFinishedAdding(result: Int) {
print(result)
}
}
let obj = Manager(developer: Developer())
obj.addTwoNumbers(num1: 10, num2: 20)
3. Delegate pattern (with closures) :
class Developer {
var didAddNumbers: ((Int) -> Void)?
func developWillAdd(a: Int, b: Int) {
didAddNumbers!(a+b)
}
}
class Manager {
var developer: Developer?
init(developer: Developer?) {
self.developer = developer
}
func addTwoNumbers(num1: Int, num2: Int) {
developer?.developWillAdd(a: num1, b: num2)
developer?.didAddNumbers = { ans in
print(ans)
}
}
}
let obj = Manager(developer: Developer())
obj.addTwoNumbers(num1: 10, num2: 20)