Learn about Delegates in Swift

Tram Ho

For iOS developers, delegate is a very familiar concept and is used a lot in Apple’s frameworks. In this article, I will show the nature and operation of Delegate through the simplest examples

What is Delegate?

In the official Apple documentation, Delegate or Delegation has the following definition:

Delegation is a design pattern that enables a class or structure to hand off (or delegate) some of its responsibilities to an instance of another type. This design pattern is implemented by defining a protocol that encapsulates the delegated responsibilities, such that a conforming type (known as a delegate) is guaranteed to provide the functionality that has been delegated

It seems a bit confusing, but I would like to summarize as follows: Delegation is a design pattern used to exchange data between structs and classes. Delegate is translated to mean delegate. Since then, between 2 classes (or structs) there will be an authorizing and authorized relationship.

To make it easier to understand, we will do the following example:

The requirement of the problem is that we can transfer data from the Owner class to the Employee class

First we need to initialize a protocol named ExampleDelegate that contains a method passData with a data parameter. After the Owner class has a property named delegate and has a type of ExampleDelegate. Then we continue to create Employee class and let it follow the above protocol. And finally, initialize 2 instances from the above 2 classes.

Did you notice that in the Owner class, there is a delegate property with type ExampleDelegate and the “employee” instance also has the same type, so we can assign it as follows:

And the unexpected thing here is that you can implement the passData method from the Owner class through the passData method inside the Employee class.

From the above example we can imagine the relationship between the principal (owner) and the delegate (employee). Own will send jobs to its employee and the employee can use the data that the owner sent (the print command in the passData method).

Apply :

If you have ever used UICollectionview, you may find the following code quite familiar

Here we can see the two delegate objects “collectionView” and the delegate is “self” (or ViewController ). collectionView authorizes the execution of the didSelectItemAt indexPath method and the delegate (aka culi ) will execute that method.

Share the news now