DEV Community

DanielJang
DanielJang

Posted on

1

Understand Protocols

When I studied Swift, It was big challenge to understand about Protocols. So I tried to summery it easily for future Daniel. 🤗

Concept of Protocols

Protocol is set of requirements without detail contents as abstract.
For example,
Here is a high school with many teachers for various class.
A requirements from principle of the school is_“Education”_to teachers with curriculum structure. The structure doesn’t include detail contents.
Alt Text

Each teacher can implement own curriculum based on the structure for students.
Then mathematic teacher implements curriculum for mathematic class.
And chemical teacher implements curriculum for chemical class.
So each teacher can implement the requirement what he/she wants based on the curriculum structure.
Alt Text

Declare of Protocols

Protocol can be defined as below

  1. Protocol keyword
  2. Protocol name
  3. Requirements Alt Text

For example by concept,
Alt Text

Adopt Protocols

Let’s learn how can adopt protocols to class or structure.
Structures and classes can adopt protocols, you add a set of colon and your add your protocol name after the name of your structure and class.
Alt Text

And the multiple protocols can be adopted with comma to classes and structures.
Alt Text

Confirm Protocols

After adoption of protocols, The requirements of the protocols should be implemented in classes or structures what adopted the protocols. We call it “Confirm the protocols”

Les’s use“Education”example again to learn confirming.
Alt Text
Alt Text

Coding practice

Let’s practice protocols by coding.

  1. Run Xcode to make a project
  2. Choose macOS template
  3. And choose “Command Line Tool”
  4. Put Product Name as “Protocols” and save project Alt Text

Alt Text

Tips

1) To adopt protocols, always the protocols should be adopted
after super class(or other inherit of class)
Alt Text

2) As you know, Classes has super class and child class for inheriting but Structures doesn’t have super structure and child structure. BUT !!! Protocols can be adopted to classes and structures for both.
Alt Text

Alt Text

Thank you for your reading.
Daniel Jang

Sentry blog image

The Visual Studio App Center’s retiring

But sadly….you’re not. See how to make the switch to Sentry for all your crash reporting needs.

Read more

Top comments (0)

Sentry mobile image

App store rankings love fast apps - mobile vitals can help you get there

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read full post →

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay