Protocol and Delegate

Here, I am going to tell a story about how to pass data between two viewControllers through Delegate.

Delegate — a note from Apple

A delegate is an object that acts on behalf of, or in coordination with, another object when that object encounters an event in a program.

Protocol — a note from Apple

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.

most importantly, which makes Protocol more powerful is

The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol. …

Story begins:

Once upon a time, two friends called -viewController and viewControllerTwo lived in two different villages. DataDelegate is the only way for them to get an update information from one to another, and DataDelegate is Protocol.

All that DataDelegate does in this story, is to define an update method. This method takes a string, which is here again, in our story, a message that viewControllerTwo wish to pass it to viewController.

In order to get an update from viewControllerTwo, Protocol -DataDelegate is adopted by viewController. Then, viewController will provide the actual implementation for the update method.

viewControllerTwo in this story is holding a message. In order to pass the message to viewController, a variable delegate of type DataDelegate is declared in viewControllerTwo. Automagically, the message is passing through via delegate.update(string: “ ”).

In the story, viewController decides to update the message in a textLabel after 2 seconds its viewDidLoad().

Here is the code that I wish that it makes more sense after reading the story.

Completed !!

Thank you for checking this article up. And don’t forget to give it some claps! 👏🏼👏🏼👏🏼 if you found it helpful.💡

--

--

Always thinking of improving

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store