Understanding delegate pattern in Swift iOS 16.08.2018

Delegation is used extensively within the Cocoa and Cocoa Touch frameworks. The delegation pattern is a very simple but powerful pattern where an instance of one type acts on behalf of another instance. The instance that is doing the delegating keeps a reference to the delegate instance, and then, when an action happens, the delegating instance calls the delegate to perform the intended function.

This design pattern is implemented in Swift by creating a protocol that defines the delegates' responsibilities. The type that conforms to the protocol, known as the delegate, will adopt this protocol, guaranteeing that it will provide the functionality that's defined by the protocol.

Delegates in five easy steps. These are the steps for setting up the delegate pattern between two objects, where object A is the delegate for object B, and object B will send messages back to A. The steps are:

  1. Define a delegate protocol for object B.
  2. Give object B an optional delegate variable. This variable should be weak.
  3. Update object B to send messages to its delegate when something interesting happens, such as the user pressing the Cancel or Done buttons, or when it needs a piece of information. You write delegate?.methodName(self, ...).
  4. Make object A conform to the delegate protocol. It should put the name of the protocol in its class line and implement the methods from the protocol.
  5. Tell object B that object A is now its delegate.
swift_delegation.png
The main benefit of delegating certain decisions and behaviors to a type's owner is that it becomes much easier to support multiple use cases without having to create massive types that themselves need to account for all those use cases.

For the example we will have a structure named Person. This structure will contain two properties of the String type, named firstName and lastName. It will also have a third property that will store the delegate instance. When either the firstName or lastName properties are set, we will call a method in the delegate instance that will display the full name. Since the Person structure is delegating the responsibility for displaying the name to another instance, it doesn't need to know or care how the name is being displayed. Therefore, the full name could be displayed in a console window or in a UILabel; alternatively, the message may be ignored altogether.

Let's start off by looking at the protocol that defines the delegate's responsibilities. We will name this delegate DisplayNameDelegate:

protocol DisplayNameDelegate { 
    func displayName(name: String) 
}

In the DisplayNameDelegate protocol, we define one method that the delegate needs to implement named displayName(). It is assumed that, within this method, the delegate will somehow display the name; however, it is not required. The only requirement is that the delegate implements this method.

Now, let's look at the Person structure that uses the delegate:

struct Person  { 
    var displayNameDelegate: DisplayNameDelegate

    var firstName = "" { 
        didSet { 
            displayNameDelegate.displayName(name: getFullName()) 
        } 
    } 
    var lastName =  "" { 
        didSet { 
            displayNameDelegate.displayName(name: getFullName()) 
        } 
    } 

    init(displayNameDelegate: DisplayNameDelegate) { 
        self.displayNameDelegate = displayNameDelegate 
    } 

    func getFullName() -> String { 
        return "\(firstName) \(lastName)" 
    } 
}

In the Person structure, we start off by adding the three properties, that is, displayNameDelegate, firstName, and lastName. The displayNameDelegate property contains an instance of the delegate type. This instance will be responsible for displaying the full name when the values of the firstName and lastName properties change.

Now, let's create a type that will conform to the DisplayNameDelegate protocol. We will name this type MyDisplayNameDelegate:

struct MyDisplayNameDelegate: DisplayNameDelegate { 
    func displayName(name: String)  { 
        print("Name: \(name)") 
    } 
}  

In this example, all we will do is print the name to the console. Now, let's see how we would use this delegate:

var displayDelegate = MyDisplayNameDelegate()
var person = Person(displayNameDelegate: displayDelegate) 
person.firstName = "Al"  
person.lastName = "Pacino" 

In the preceding code, we begin by creating an instance of the MyDisplayNameDelegate type and then use that instance to create an instance of the Person type. Now, when we set the properties of the Person instance, the delegate is used to print the full name to the console.

While printing the name to the console may not seem that exciting, the real power of the delegation pattern comes when our application wants to change the behavior. Maybe we want to send the name to a web service or display it somewhere on the screen, or even ignore the change. To change this behavior, we simply need to create a new type that conforms to the DisplayNameDelegate protocol. We can then use this new type when we create an instance of the Person type.

One more example of delegate in Swift.

Another advantage that we get from using the delegation pattern is loose coupling. In our example, we separated the logic part of our code from the view by using the delegate to display the name whenever the properties changed. Loose coupling promotes a separation of responsibility, where each type is responsible for very specific tasks; this makes it very easy to swap out these tasks when requirements change, because we all know that requirements change often.

Delegates are very popular in iOS world. For example, UIApplication (our application main class) delegates the control of the interaction between the app and the iOS.

The AppDelegate class contains some key methods, which are cool extension points.

There is a function which is called once the app goes into background mode (the user switches to another app) and when it goes to foreground mode (the app was activated).

The delegate is in a good place to respond to incoming notifications (such as push notifications, memory warnings, and download notifications). In short, these are external events, sent from the iOS, which the app could handle.