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.

Example

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.

Analogy

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
2
3
protocol ProductSelectionDelegate {
func didSelectProduct(name: String, imageName: String)
}

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
var delegate: ProductSelectionDelegate?

Next, the main view controller applies for the job by conforming to ProductSelectionDelegate.

1
class ViewController: UIViewController, ProductSelectionDelegate

Now that the main view controller has signed up for the job, it must implement the required method.

1
2
3
4
func didSelectProduct(name: String, imageName: String) {
productNameLabel.text = name
productImageView.image = UIImage(named: imageName)
}

The main view controller can now say, “Sign me up. I want to be your delegate.”

1
2
let destinationVC = ProductSelectionVC()
destinationVC.delegate = self

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@objc func iPhoneButtonTapped() {
delegate?.didSelectProduct(name: "iPhone 14", imageName: "iphone")
dismiss(animated: true)
}

@objc func iPadButtonTapped() {
delegate?.didSelectProduct(name: "iPad Air", imageName: "ipad")
dismiss(animated: true)
}

@objc func macBookButtonTapped() {
delegate?.didSelectProduct(name: "MacBook", imageName: "mac")
dismiss(animated: true)
}


Swift Delegate Protocol Pattern
http://runningcoconut.com/2024/08/13/Swift-Delegate-Protocal-Pattern/
Author
Huajing Lu
Posted on
August 13, 2024
Licensed under