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.
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.
Declare of Protocols
Protocol can be defined as below
- Protocol keyword
- Protocol name
- Requirements
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.
And the multiple protocols can be adopted with comma to classes and structures.
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.
Coding practice
Let’s practice protocols by coding.
- Run Xcode to make a project
- Choose macOS template
- And choose “Command Line Tool”
- Put Product Name as “Protocols” and save project
Tips
1) To adopt protocols, always the protocols should be adopted
after super class(or other inherit of class)
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.
Thank you for your reading.
Daniel Jang
Top comments (0)