DISCLAIMER: This post is older than one year and maybe out of date.

Classes – Intermediate

A few concepts for taking your understanding of Classes to the next level in Swift. I am certain many if not all of these are techniques you will use over and over. This post continues on where Swift Classes – The Basics left off, so if you are not familiar with classes you will want to check out that post as well.

Subclassing a Class

There are many times you will want to take an existing class that either you or someone else created and change it in some way to suit your current need, to do that we do what is called subclassing where we say ‘I want the functionality of this class but with a little something extra’. Think of it as buying that Ferarri but adding the fluffy dice and peace sign as after market parts!

It is worth noting for anyone that is used to Objective-C that we set the properties of the subclass before calling the init of the super class, this is backwards to some other languages as you may have noticed. A class is not considered fully initialized until both it’s own properties and any super class properties have been initialized, you should remember this as you design your inheritance and take it into consideration. You will find that Swift will help you out here but not compiling if you get it wrong!

Overriding Properties in Subclasses

We can override properties and methods from our super class by simply telling it to do just that, override. This is another example of the Swift ‘Safe’ way of doing things.

Property Observers

There are times you will want to have some kind of automatic notification when a property changes and maybe even execute some code. To do this we use something called Property Observers it is hard to not think of these as working similar to other languages that use an event system with listeners. There is two parts to this one called willSet and another called didSet, I have commented in the example code the differences to better explain what is happening.

In this example we have a class that runs our lottery machine, each time a number comes up the observer kicks in to check and see if it matches the winning number, if it does then we have a winner. The odds are pretty favorable on this lottery, not the greatest business plan 🙂

Hopefully there are some things to take away from this post for you, in particular subclassing is something you will find yourself doing throughout any programming language.

Share Button