Delegation Pattern in Swift 4.2

What is Delegate Protocol in Swift? | optional and required Protocol methods?

What is the Protocol?

According to Apple Documentation-
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.
In addition to specifying requirements that conforming types must implement, you can extend a protocol to implement some of these requirements or to implement additional functionality that conforming types can take advantage of.

The protocol you have seen so many time in Swift language while developing basic table view there UITableViewDelegate & UITableViewDataSource. Both protocols having their own methods required and optional. If you have seen in Apple’s frameworks.

If you press the command key () and mouse left button click on UITableViewDataSource you will able to see these options there -

UITableViewDataSource Protocol

Now click on Jump to Definition, then you will see their protocol methods -

Table View 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 and how to apply inside our project.

This part is related to the Delegation pattern so i will cover here little bit part related to the Protocol. I will cover Protocol in the separate part.

How to create your protocol?

Let’s start with write protocol out of the class and you will able to see something like this -

choose first option or press enter. After that, it will look like this.

Now write your protocol name and requirements with your function and variables, which you want to use with your protocols. I have created one protocol with the name DeveloperEntryDelegate and I am using here AnyObject because if you want to make it weak then you have to use it otherwise you can ignore it.

Protocol Declaration -

protocol DeveloperEntryDelegate{
func textDeveloperPlatform(_ text: String)
func textDeveloperLanguage(_ text: String)
}

Applying in the Class-

weak var delegate: DeveloperEntryDelegate?

You will be see below error for weak protocol declaration -

weak protocol error

Now fixing this error with protocol type AnyObject

protocol DeveloperEntryDelegate: AnyObject {
func textDeveloperPlatform(_ text: String)
func textDeveloperLanguage(_ text: String)
}

Now see your class, where we are going to declaring it.

Protocol with delegate name

Now see how it will work?

Essentially delegate we are using for the call back for passing values or methods from one call to another class. This will one to one communication.

Delegation Example

In this example, we can able to see from the first view to second view navigating and writing in the textfields. After clicking on Done button in secondViewController delegate methods passing back to FirstViewController text entry data with the DeveloperEntryDelegate protocol methods. It’s very helpful when you want to do some changes from one view to another view. It’s very easy to use. You can find this example on Github.

Inside FirstViewController-

class FirstViewController: UIViewController {
@IBOutlet weak var labelPlatformDetails: UILabel!
@IBOutlet weak var labelDeveloperLanguage: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
//MARK: - Navigation
@IBAction func actionAddDetail(_ sender: UIButton) {
guard let secondView = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController else {
fatalError("View Controller not found")}
secondView.delegate = self //Protocol conformation here
navigationController?.pushViewController(secondView, animated: true)}
}
//MARK: - Protocol Delegate Methods
extension FirstViewController: DeveloperEntryDelegate {
func textDeveloperPlatform(_ text: String){
labelPlatformDetails.text = "Platform: \(text)" }
func textDeveloperLanguage(_ text: String) {
labelDeveloperLanguage.text = "Language: \(text)" }
}

And inside SecondViewController-

protocol DeveloperEntryDelegate: AnyObject {
func textDeveloperPlatform(_ text: String)
func textDeveloperLanguage(_ text: String) }
class SecondViewController: UIViewController {
weak var delegate: DeveloperEntryDelegate?
@IBOutlet weak var textPlateform: UITextField!
@IBOutlet weak var textLanguage: UITextField!
override func viewDidLoad() {
super.viewDidLoad() }
  //MARK: - Action Pass back view Details
@IBAction func actionDone(_ sender: UIButton) {
self.navigationController?.popViewController(animated: true)
self.delegate?.textDeveloperPlatform(textPlateform.text ?? "")
self.delegate?.textDeveloperLanguage(textLanguage.text ?? "")
}
}

How to make Optional Protocol method ?

By adding @objc with your protocol and with @objc optional method you can make it. 👍🏽

@objc protocol DeveloperEntryDelegate: AnyObject {
func textDeveloperPlatform(_ text: String)
@objc optional func textDeveloperLanguage(_ text: String)
}

If you want to make it another way optional method for your protocol. You have to create the extension for your optional protocol methods. 😎 🎉

protocol DeveloperEntryDelegate: AnyObject {
func textDeveloperPlatform(_ text: String)
func textDeveloperLanguage(_ text: String) //optional method
}
//optional method
extension DeveloperEntryDelegate {
func textDeveloperLanguage(_ text: String){}
}

Conclusion

The Protocol delegation pattern is the most important part of the Apple’s frameworks also you can implement inside your code for communication one class to another class easily. Some developers I have seen initial step no one has that much of idea for passing values from one view to another view so they trying to deal it by saving values locally with the UserDefaults or by using global variables. This will be the not the right choice by the way if you having any local storage functionality but again you have to fetch it. So delegate make if more simple for fast process. 🎉

In this part, we have seen what is protocol. How to create it and how to work with the delegation pattern. After that also you got understanding with optional and required protocol methods. By the default, methods will be required. If you want to make it more flexible than you can make if optional methods. I hope you enjoy it. 😊✌🏼

Thanks for reading 🙌🏼

If you having any query regarding this tutorial ? | If you think you can do more simple way or little bit more extra things with this stuff please let me know questions, feedback or comments -on Twitter