Swift Delegates and Protocols

How often we see two screen sharing information with each other or passing data from one screen to other screen or just communicating. This is achieved with the help of Communication Pattern.

What is Communication Pattern? As the Name suggest communication, passing information from one screen to other or sharing data from one screen to other through a specific set of rules and regulation is known as Communication Pattern. It is one of the most used and important Design Pattern in iOS programming. Communication patterns are of two types Delegates and Protocols and Notification and Observers. In this tutorial we will be focussing on Swift Delegates and Protocols.

Before we get deep into the aspect of Swift Delegates and Protocols I assume you’ve basic understanding of iOS Development using Swift.

Lets break both the word Delegates and Protocols and try understand what they actually mean. Delegates as the name suggests, delegation i.e. your representative or someone on your behalf. Protocols on the other hand means a set of rules and regulation.

Protocols

As Apple says A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol. You can read more about Protocols here.

Delegates

As said earlier, delegates means someone on your behalf i.e. giving responsibility to other. Imagine ViewController1 calls a ViewController2 to do certain task, Once the task is completed ViewController1 should know that ViewController2 has completed it task so that it can take necessary action.

So without wasting time let’s get started!!! As usual we will be developing complete tutorial stepwise to get better understanding. Here we would be developing a simple application with two screens, Screen1 and Screen2. On tapping change background color button on Screen1 it will take us to screen 2 where we can select one color either red or cyan. On selecting one color it will dismiss the current Screen2 and open Screen1 with background color updated to the one we selected on Screen2.

Step1: Create Project

Open Xcode, New Project, Single View App and name it as DelegateProtocols.

Create New Project
Create New Project

Step 2: Let’s develop User Interface

Open Main.Storyboard and add One more View Controller and name it as View Controller2, rename the existing View Controller to View Controller1. Add new File ViewController2 subclass of UIViewController and add it as class of View Controller2.

Create a button name it “Change Background Color” in View Controller1 and add label ViewController-1, Create two button in View Controller 2 change the background color to cyan and red, add label ViewController-2.

Main.Storyboard
Main.Storyboard

Step 3: Create Instances

Create Button instance @IBAction for ViewController1 and name it as btnChngBgColor, Similar way create Button instance IBAction for both buttons in ViewController2 and name it as btnChngBgColorCyan, btnChngBgColorRed respectively.

In ViewController1 add below code in @IBAction func btnChngBgColor for navigation from ViewController1 to ViewController2

 
@IBAction func btnChngBgColor(_ sender: Any) {
        let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let viewController2 = storyboard.instantiateViewController(withIdentifier: "viewcontroller2") as! ViewController2
        self.present(viewController2, animated: true, completion: nil)
    }

Similarly In ViewController2 add below code in  @IBAction func btnChngBgColorCyan and also in @IBAction func btnChngBgColorRed

You can take a pause run the application and check whether you can navigate from Screen1 to Screen2 and vice versa.

 self.dismiss(animated: true, completion: nil) 

Step 4: Create Protocols

In the ViewController2.swift add below code before class declaration and below import statement.


protocol ViewController2Delegate {
    func changeBgColor(color: UIColor)
}

Here we’ve created Protocol ViewController2Delegate and defined the function changeBgColor(color: UIColor). Now declare the reference of this protocol in class ViewController2, i.e. Create a delegate property.

     var delegate: ViewController2Delegate?

Step 5: Add delegate method call

Since we’ve already created a button instance in Step 3 we only need to add delegate method call here follow the below code.

     @IBAction func btnChngBgColorCyan(_ sender: Any) {
         self.delegate?.changeBgColor(color: UIColor.cyan)
         self.dismiss(animated: true, completion: nil)
    }
    
    @IBAction func btnChngBgColorRed(_ sender: Any) {
        self.delegate?.changeBgColor(color: UIColor.red)
        self.dismiss(animated: true, completion: nil)
    }
    

That’s it we’re almost done, your ViewController2 should finally look like this

Full Code ViewController2
Full Code ViewController2

Step 6: Conform the Protocol

Open ViewController1.swift, Write extension and conform the class to ViewController2Delegate

extension ViewController1: ViewController2Delegate {
}

Step 7: Implement the functions of Protocol

As we know if our class conforms to any Protocol we need to implement the mandatory methods of that protocols let’s implement the method changeBgColor(color: UIColor)

 func changeBgColor(color: UIColor) {
        self.view.backgroundColor = color
    }

Step 8: Set the delegate

This is the last step where we set the delegate. Before navigating to ViewController2 on button action add below code.

  viewController2.delegate = self 

Your final ViewController1 should look like this

Full Code ViewController1
Full Code ViewController1

We’re done run your application!!!

Comment below for any queries!!