Implementing Delegation in Swift

Delegation is a simple and powerful pattern in which one object in a program acts on behalf of, or in coordination with another object. The delegating objects keeps a reference to the other object-the-delegate-and at the appropriate time sends a message to it.

       The most common way of delegation that found in Apple's own API's is by using delegate protocols. Just like how UITableView has a UITableViewDelegate protocol.

UITableViewDataSource protocol methods

That was the one example for Protocols in Swift. Now see what is this and how to create our own protocol methods.

Let's see how to pass Data using Swift Delegate Protocol

1) Create a New Project using XCode i..e, File -> New -> Project

2) Create a new in the project i.e., "FirstViewController"

3) Create a User Interface in main.storyboard and setup Interface Builders to the controllers

4) Create two buttons in each controllers i.e., "Push" and "Back" to pass data between the two controllers.

    Till here we are done with the setting up User Interface, lets start implementing the delegation by creating a protocol in ViewController as below

                         import UIKit
                         protocol callBackDelegate: class {
                            func displayAlert()


Create a protocol object in FirstViewController as       

                               weak var delegate: callBackDelegate?

Setup FirstViewController navigation from ViewController on pressing button
   @IBAction func push(sender: UIButton) {
        let firstView = self.storyboard?.instantiateViewController(withIdentifier: "firstController") as? FirstViewController
        firstView?.delegate = self
        self.navigationController?.pushViewController(firstView!, animated: true)

Here "push" is the name UIButton Action which pushes to FirstViewController

Call Protocol method when user taps on the back button in FirstViewController

   @IBAction func back(sender: UIButton) {
        self.navigationController?.popViewController(animated: true)


Inherit callBackDelegate protocol in ViewController which ads the protocol stubs

class ViewController: UIViewController, callBackDelegate {
    func displayAlert() {
        let alert = UIAlertController(title: "Intruder Alert", message: "Display Alert Success", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        self.present(alert, animated: true, completion: nil)

Done, and now let's see the output