Swift Delegate Protocol Pattern
Swift Delegate Protocol Pattern
The delegate pattern is a one-to-one communication pattern in Swift that allows one object to communicate with another.
Example
The view controller in the bottom sheet communicates with the main view controller. When a button is tapped, the main view controller updates the UI.

Delegate
A delegate waits to be told when and what to do. We do not call the delegate method from the delegate itself; the delegating object calls it when an event occurs. As an analogy, consider a boss and an intern. The product selection view controller is the boss: it knows what was tapped and passes that information to the main view controller.

In the product selection view controller, which acts as the boss in this example, we create a protocol. The protocol lists the required commands, much like a job description.
1 | |
We also need an “intern” on the product selection screen. We create a variable named delegate with the type ProductSelectionDelegate; this is like defining a job position.
1 | |
Next, the main view controller applies for the job by conforming to ProductSelectionDelegate.
1 | |
Now that the main view controller has signed up for the job, it must implement the required method.
1 | |
The main view controller can now say, “Sign me up. I want to be your delegate.”
1 | |
Finally, the product selection view controller—the boss in this example—gives the order. It is effectively saying, “Do your job, delegate. Here is the information you need.”
1 | |