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)