DEV Community

DanielJang
DanielJang

Posted on

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

Discussion (0)