Understanding of the protocol in Swift

Fredric Cliver
2 min readApr 25, 2020

A protocol is hard to understand. and It contains different concept, Delegate and Extension.

Let’s take a look with pseudocode, not real code with a hundred lines.

First of all, you may imagine this situation

There are two views

There are 2 views and parent_view has child_view as embedded. I’ll put the all the thing to delivery something to parent_view from child_view.

Make a Protocol
  • Implement a protocol. and define a function in there. but you don’t need to implement code in the function. Just define name and variables only.
make an instance of protocol and call the function of the protocol
  • In there ViewController of child_view, make a new instance as the Protocol (the name is not ‘Protocol’ it is your own)
  • call the function on your wish, any place.
set the Class as a delegate you want to receive a notifying

But you need this first. In the ViewController of parent_view, you have to set the instance of Protocol in child_view to the parent_view itself.

Finally, the parent_view can be notified from child_view through the protocol and delegate. but, after notifying, we need more custom actions in the parent_view. So for that, add this extension to the parent_view.

extend the receiver class as the Protocol. and implement actions when you get notifying

The extension has to be inherited from our the Protocol. and we have to add function implementation on the extension.

That’s it for all.

--

--

Fredric Cliver

Majored in Physics, self-taught and worked in the IT industry as a Dev/Design/Planning for 11 years. And I had run my Startup for 3 years. I fancy a ☔️ 🇬🇧