The Delegation Design Pattern

If you have ever tried your hand at swift programming you might have come across the term “Delegate”. It is something that is used widely across any swift app. At first the term might sound complex but the Design Pattern concept is actually very simple (and powerful).

What is Delegation?

Imagine that you would like to build your dream house. Your first step might be to create a list that enumerates every task needed to finish your house

  1. Architecture
  2. Interior
  3. Electrical
  4. Paint
  5. Foundation

This list has tasks that require very different skills. You might be able to do one of them but trying to do all of them wouldn’t really result in a perfect “dream” house.

Therefore the solution is to “delegate” the tasks to other professionals. You can hire an electrician to do the electrical of your house or find an architect to help you make a design. This verb “delegate” literally means “to entrust (a task or responsibility) to another person”.

How this is applied to Swift programming

A delegate in swift is simply an object that conforms to a Protocol (My blog post explaining Protocols).

For example, a Table View in swift is a Delegator. This means that the Table View delegates some tasks to whoever conforms to its protocol. Usually these tasks are view events. (Like when a user selects a row or when a row is highlighted)

An example of a delegated task in a Table View is tableView:didSelectRowAtIndexPath. (Which is the didSelectRowAtIndexPath method from the UITableViewDelegate protocol) This task is sent to the Table View’s delegate (the class that will handle the tasks) when the user selects a row from a Table View. That way it is not up to the Table View (the delegator) but the class (the delegate) to determine what happens when the user selects an item from the Table View.

This process of the View (in our case a Table View) delegating tasks to another class (usually a View Controller) helps maintain the MVC (Model View Controller) design that is so important in Mobile Development. It would be improper for the Table View to define the actual code that gets executed at these events.