Junior — Middle
Can you explain the concept of delegation in design patterns and how it is applied?
sobes.tech AI
Answer from AI
Delegation is a design pattern in which one object passes the execution of a specific task to another object, called a delegate. This allows for responsibility sharing and increases code flexibility.
In iOS, delegation is often used to pass events or data between objects. For example, UITableView uses a delegate to handle cell selection or appearance customization.
Example in Swift:
protocol MyDelegate: AnyObject {
func didFinishTask()
}
class Worker {
weak var delegate: MyDelegate?
func startTask() {
// Perform the task
// ...
delegate?.didFinishTask()
}
}
class Manager: MyDelegate {
func didFinishTask() {
print("Task completed")
}
}
let worker = Worker()
let manager = Manager()
worker.delegate = manager
worker.startTask()
Here, the Worker object delegates the notification of task completion to the Manager object.