Muhammad Harits Syaifulloh

Friday, November 4, 2016

Swift 3 - Inheritance In Swift 3

Swift 3 - Inheritance In Swift 3

Previously we've looked at Classes and Objects in Swift 3. Now can you imagine trying to write a class that covers cars, who pays, trucks, family cars, etc. Well there would be quite a lot of of repeated code and as I said before we cannot repeat code because that's bad. So this is where inheritance comes in and save us a lot of trouble. Let's see how inheritance works by implementing some of it in our playground.

Let's create a class which is called just simply "MacBook" and we're going to give this class only one property let processorType = "Core i5", so it will look like the following picture:


Then let's say we want a family class, well let's have a class called FamilyMacBook. Now I could initialize this class and say let processorType = "Core i5". But hey, I've repeated code and that's bad. At least I've told you that's bad, so delete that!.


And what we're going to do is make FamilyMacBook inherit from MacBook, so it grabs all of the properties methods and things available in class MacBook and assign them to FamilyMacBook. Then inside of FamilyMacBook, you can add various other properties that only sit with FamilyMacBook.


Now if I created a var familyMacBook = FamilyMacBook(), we can now access both the processorType and storageSize. So let's have the following code:


So our playground tells us "Core i5" and "128 GB", and our FamilyMacBook has inherited from the class of MacBook. Now we can imagine this inheritance can actually keep going on and on. I could create a class called BigFamilyMacBook and this would inherit from just the plain old FamilyMacBook, so BigFamilyMacBook get all of those properties in FamilyMacBook. But because FamilyMacBook inherits from MacBook, BigFamilyMacBook also gets the processorType that's available inside of MacBook.


So that's basically how inheritance works, and if I wanted to initialize a class I could put my init into class of MacBook. So let's have the following code :


And now we have our line at the bottom it tells us we have Core i7 processor on our MacBook. So that's how inheritance works and again it's a fundamental principle that we going to see every single time we open up our iOS projects. So thank you very much for visit my blog and I hope it well be easy to understand. If you have any question just leave some comment below and see you next time in the next tutorial.

No comments:

Post a Comment