What Are Protocols?
According to Apple’s Swift Documentation page a protocol is defined as:
[…] a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements.
So protocols are like certificates that are adopted by a class, structure, or enumeration.
Since I’m currently learning how to drive by car, let’s take this example to understand protocols better.
The Mandatory Traffic Course As Analogy for Protocols
Some days ago, I completed a boring course that each nascent car driver has to pass.
It’s called the VKU (Verkehrskunde for those who understand German), a four-day course where you learn theoretical aspects about the car and the traffic you must cope with while driving.
Having this certificate proves that you satisfy a bunch of requirements, and you are now able to register yourself for the driving exam.
Now the question arises how do protocols look like in Swift. Here is it:
Defining A Protocol, A Certification respectively
As you can see in the picture above, a protocol is similarly defined to classes, structs, and enumerations. It starts with the keyword “protocol,” followed by the capitalized name and a set of curly brackets. Inside them are a bunch of requirements defined.
When a class or struct adopts this protocol, it’s able to meet the protocol requirements and have the skills listed in the protocol (in the picture on line 7 and 8).
Conclusion
What we’ve learned today is that protocols can be understood as certificates. A class or struct who adopted a protocol can meet the requirements and have the protocol’s skills.
If this article resonated with you, be sure to recommend and share.