Delegates And Closures

Wilson Balderrama
2 min readNov 24, 2016

--

In this post I will use the same example applying first Delegates and then Closures, let’s dive into it.

Delegates

Let’s suppose there is a client that wants to have a developer build his website:

So he decide to find a developer but someone told him that he’d better find a developer specialized on web development.

He thought: “if I hired a developer, he would need to prove me that he’s specialized on web stuff” and he saw convenient that the potential candidate should follow a protocol to know that he’s the right one:

And in this way the client will feel confident that his website will be built by someone that knows his stuff.

So that the client will delegate the task to someone that follows a protocolWebDeveloper because this will ensure that the developer knows how to make websites:

Then the client finally not only finds a Engineer also realizes that he’s specialized on web stuff and he follows the protocol WebDeveloper:

He hires and delegates him to do the job:

So you can see that the engineer is stored in the delegate variable and this variable only accepts a WebDeveloper type and because Engineer type conforms the WebDeveloper protocol, this is why this assignation is successful.

And finally client calls his haveDeveloperBuildMyWebsite method that internally calls delegate?.makeWebsite.

Closures

Continuing with the example of above.

It happened to be that the client didn’t like the job and also he spent too much money on it.

After much thought he decided to try again working with another person but this time he didn’t want to spend too much money.

So he lowers his expectations and decides that as long as the person has the skills, the person could be hired.

But this time the client is only interested on the person’s ability to make websites, so he uses a closure for storing the person’s ability.

A little while after, he hires another person:

And instead of requiring to store the enthusiast as a delegate, the client only store enthusiast’s makeWebsite method as a closure to make his website.

At the end the client will call the closure from haveDeveloperBuildMyWebsite method, and the closure is referring to enthusiast’s makeWebsite instance to finally have his website develop.

We could see the use of Delegates and Closures in this example, certainly both of them allows us to run code that belongs to another source behind another entity.

It will depend on the specific situation which approach fits better on the problem but in my humble opinion I think when more than one method is required, a Delegate will be a better option and on the other hand if one only one method is required, then a Closure should be a good solution.

--

--

Wilson Balderrama

I like to run everyday while listening podcasts or audiobooks, read/write at Medium and of course I try to improve my skills as an iOS Developer everyday.