Creating Delegates in Swift

A Brief Introduction

Christopher Webb
Journey Of One Thousand Apps
2 min readMay 11, 2017

--

Overview

As you might have noticed, Apple is pretty trigger happy when it comes to providing delegate in its libraries. There is UITableViewDelegate, UITextFieldDelegate and of course, your AppDelegate. Delegation is one of the key software design patterns in Object-Oriented programming. This pattern allows one class to hand off some functionality to another.

The Apple-y Explanation

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 object keeps a reference to the other object — the delegate — and at the appropriate time sends a message to it. The message informs the delegate of an event that the delegating object is about to handle or has just handled. The delegate may respond to the message by updating the appearance or state of itself or other objects in the application, and in some cases it can return a value that affects how an impending event is handled. The main value of delegation is that it allows you to easily customize the behavior of several objects in one central object.

Diving In

Let’s imagine for a second you want to detect a button tap in your view and do something accordingly in your ViewController.

Analysis

Does it work? Sure, but there is another way to do this where we don’t have to attach our button and ViewController directly.
We can create a delegate method to have MainView be the intermediary between the two. Doing this allows better for encapsulation of data and behaviors within respective classes.

Let’s first create our protocol:

This is relatively straight forward. We have a class protocol called MainViewDelegate which specifies the method:

func searchButtonTappedWithTerm(with searchTerm: String)

To be able to use this delegate in code we need to add it our MainView as a weak optional property. Why weak? Because we don’t want to have our ViewController and delegate locked in a strong reference cycle that stays in memory without being deallocated. That’s a great way to cause a memory leak.

To access this functionality we need to make our ViewController conform to the MainViewDelegate protocol like so:

We can now do something with the textfield text in our ViewController without having to access it directly.

Recap

The final ViewController code for this example looks something like:

The great thing about delegation is that there are a wealth of ways to implement them beyond this example. Figuring out where and when to use them is the key.

Sources:

https://developer.apple.com/library/content/documentation/General/Conceptual/DevPedia-CocoaCore/Delegation.html

--

--