This part of the Swift language is pretty simple to explain. A “Protocol” is what is called a “Interface” in most of the other languages out there. It is basically a set of rules that your struct, class, or enum has to conform to.
You maybe asking your self “why would I ever need this weird construct ? I know whats what. I don’t need these things if I am doing it all myself. ” Well thing is that it keeps you honest, and it keeps you on track.
More importantly it opens the door to things like delegates. More on this in my next blog post.
Long story short, it helps you with the turning nothingness into somethingness, or at least simulates a sort of nothingness.
In most languages out there like C#, if a variable does not get initialized with a value or is not set to any value, it’s value is “null”. Knowing this, you can go about your life as programmer knowing that you just have to check if that variable is null before using it, and your good 😎
However with Swift that is simply not the case. That is due to the fact that the Swift language does not allow variables to be “null” (In Swift its “nil”) at runtime. It believes that every variable has to have some sort of value. To combat this Optionals came into existence. What Optionals do when Swift asks them if a variable is “nil’, is reply with a “maybe, who knows” and Swift moves on.
Literally speaking here Optionals are just a offshoot of your standard variable that may or may not contain a value. This way your never left wonder why something didn’t have a value, when you thought it would.
Heres a coding example shown below: