Simple Explanation of Swift Delegate
Problems
- Simple explanation of delegation design pattern?
- What is the advantage of it?
Scenario
Let’s assume you are a labour in a company, providing coffee mug cleaning services. You have two clients to serve, client A and client B.
You signed the contract CoffeeMugCleaningServiceContract with the two clients.
Both clients are busy and will just send a phatom representative delegate to the pantry. This representative only report the event defined in the CoffeeMugCleaningServiceContract. When you run the cleanMug() service you would notify that representative that the mugs are cleaned.
In Swift world, it would be represented like:
Your Contract signed with the two clients:
protocol CoffeeMugCleaningServiceContract: class {
func mugsDidClean()
}
Your (Labour) class:
class Labour {
var delegate: CoffeeMugCleaningServiceContract?
func cleanMug(){
// some cleaning work
delegate?.mugsDidClean()
}
}
Your Client A and B classes:
class ClientA: CoffeeMugCleaningServiceContract {
prepare(){
labour.delegate = self
}
func mugsDidClean(){
print("ok noted")
}
}
class ClientB: CoffeeMugCleaningServiceContract {
prepare(){
labour.delegate = self
}
func mugsDidClean(){
print("thanks")
}
}
Using delegate would decouple you and your clients, so the labour can serve many different clients WITHOUT changing code, as long as they sign up the same service contract with you
In contrast of not using delegate
Your (Labour) class:
class Labour {
func cleanMugForA(client: ClientA){
// some cleaning work
client.mugsDidClean()
}
func cleanMugForB(client: ClientB){
// some cleaning work
client.mugsDidClean()
}
func cleanMugForC(client: ClientC){
// some cleaning work
client.mugsDidClean()
}
func cleanMugForD(client: ClientD){
// some cleaning work
client.mugsDidClean()
}
...
}
Your Client A and B and … classes:
class ClientA: CoffeeMugCleaningServiceContract {
func mugsDidClean(){
print("ok noted")
}
}
class ClientB: CoffeeMugCleaningServiceContract {
func mugsDidClean(){
print("thanks")
}
}
Now your labour class needs to add new code to cater new clients, which means they are tightly coupled
Comments