Before start reading this article, I’d highly recommend that you please go ahead and read my following articles.
As usual lets setup our base protocols and classes as below. I hope the code below is self explanatory if you have read my previous article on Protocol.
Let’s create some objects now and manipulate the values as below
Now it’s time to write some extension for the protocol. This is where things get interesting.
So what actually happens above? Let me explain.
First we have created an extension for the protocol WarCapable. Now inside the extension we have implemented a function. Main difference here in extension is that we are implementing the function but in protocol we will only define the function.
Let’s run some test and check that.
As you can see above we can compare the top speed of both Tanks and SpyJeeps. But here both Tanks and SpyJeeps are conforming to the WarCapable protocol. What if they don’t? Let’s create another Class and then some objects and check it out.
First create a SpyBike class and confirm it to SpyCapable protocol
Now let’s create some objects for SpyBike
Now if you try to access canTravelFaster method from the WarCapable extension you’ll be thrown with an error. Obviously SpyBike doesn’t conform to WarCapable so it’ll not work
Or other way around will also throw an error as below for the same reason above
As you have guessed, the methods inside the extension will work only with the classes that has confirmed to the mother of that extension. In this case it’s WarCapable.
If I put everything we’ve done so far in one single file. It should look something like below.
Hope you’ve learned some more about protocol out of this tutorial. Good luck!
Subscribe to our mailing list
Subscribe to our mailing list and receive a free udpates
Thank you for subscribing.
Something went wrong.