Learn iOS SpriteKit with Examples, Code Snippets and Video Tutorials

Swift Basics – Part 9 – Subclasses

Swift Basics – Part 9 – Subclasses
October 17, 2014 Justin

I think subclassing is on the borderline of what I would consider “the basics”. Conceptually it can be a bit hard to know when you really benefit from subclassing a class. So if you can’t imagine exactly when or why you should do this, don’t sweat it for now.

So what is a subclass? It is a class that inherits the properties of another class (it’s super class), and can then extend the functionality of that class and set different properties. To illustrate this, let’s first create a class of Enemy, which will be our super class. We don’t need many properties to make this happen, so think for a moment what all game enemies have in common?…. Got it? They usually all do damage to the player and receive damage.

Next let’s write a subclass of Enemy named Turtle.

To specify it is a subclass, we simply put a colon between the class name of Turtle and the super class of Enemy.

We can create an instance of the subclass in the usual way, like so…

Now turtleRed has three properties. Two from the super class: health and damageToPlayer, and one from it’s own class: playerCanBounceOffShell.  You could change any of them after creating the instance in the usual ways. For example…

Changing default values of the super class

A subclass can alter the default values of properties in the super class in an init statement of the subclass.

This looks a bit tricky, but follow the logic here. We write override init  because the subclass is going to use it’s own init statement, but you’ll notice on the next line we immediately call super.init() which initializes the super class, and any properties there will have their default values assigned. BUT then we have an opportunity to change those default values in our subclass, and you see that now we can set damageToPlayer to 5.


Functions and How to Override Them

We just saw one example of how to override the init statement, and we can do the same thing with functions in the super class. So for example, lets add to our Enemy class a function called witherAndDie….

Then in our Turtle class, let’s override that.

So if we called…

… that would output “do something more specific for turtles”.

Not too hard to understand, right?

Justin Dike is the owner and lead developer at CartoonSmart.com. He's taught hundreds of hours of game development video tutorials, covering everything from coding to art. These days he's working mostly on Swift and Sprite Kit tutorials, which often lead into highly polished iOS / tvOS Starter Kits, which require no programming at all, but are capable of making nearly any type game! Yeah, you read that write. You can also find Justin at the official CartoonSmart Podcast


Leave a reply

Check out our premium Swift and Sprite Kit Tutorial content!

Visit CartoonSmart.com