Understanding of the protocol in Swift

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.

--

--

--

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 ☔️ 🇬🇧

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

Recommended from Medium

My perfect Azure development environment

From Prototype to Work of Art

“Osoroi Code” — How to be dressed like your beloved ones

Perils of pseudo-programming job

What is InsureDAO?

DevOps with GitHub — Part 2: Building and Publishing Packages with GitHub Actions

Building Ontologies with Python

A real practice to handle “unrelated build file” error from Gradle

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
Fredric Cliver

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 ☔️ 🇬🇧

More from Medium

Batch Convert XCode String files, from utf-16 to utf-8

Pulling real time data with WebSocket and SwiftUI

Prevent Homebrew services from starting automatically

Switch Statement in Swift