Delegates in iOS
Mobile App Development

Understanding Delegates in iOS – Swift

What is a delegate?

Delegation is a simple and powerful pattern in which one object in a program acts on behalf of, or in coordination with, another object.

A delegate allows one object to send messages to another object when an event happens. 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.

Example:

For example, if you’re downloading data from a web site asynchronously using the NSURLSession, One or more of NSURLSession delegates will get called when NSURLSession encounters a failure, success, or received a response from the web site. For a better explanation,

The client reports a bug. The project manager creates an issue and tells one of the developers to fix the problem asap.

So at some point, an event happened, so the delegator (manager) utilized an external resource (a developer) using a common interface (issue describing the problem for both parties) to do achieve something (fix the bug).

A simple example of a custom delegate between two view controller,

Step 1:Create a Protocol
protocol Work: class {
func doSomething()
}

Step 2 : Create method on first view controller
class Employee: Work {
func doSomething() {
print(“Working on it”)
}
}

Step 3:Set delegate
class Manager {
weak var delegate: Work?
func passAlong() {
delegate?.doSomething()
}
}

Step 4: Confirm delegate
let manager = Manager()
let developer = Employee()
manager.delegate = developer
manager.passAlong() // PRINTS: Working on it

Delegates… Interesting, isn’t it?

This is just the begining! Want to implement this in your next project? Talk to Us

One thing you need to know that I’m not explaining every little detail or protocol here. When looking at these codes above, I want you to think about what’s going on so you get a basic idea of what’s a delegate is. As a conclusion, keep reading and to work on this in your next project — Work with Us!

written by
Amit Goswami
Amit Goswami Lead iOS Developer