Learn iOS SpriteKit with Examples, Code Snippets and Video Tutorials

Swift Basics – Part 8 – Class Initializers

Swift Basics – Part 8 – Class Initializers
October 16, 2014 Justin

This Swift tutorial video continues right where the previous video semi-abruptly leaves off. Translation: it just got too long for one single video. So we’ll break it into two parts like Hollywood would. Which means we’ll also continue writing our hypothetical MarioBrother class right where we left off.


Initializers

If you remember from the previous video, our struct had what was called a member wise initializer for us to set property values right away. Classes can do the same thing by passing parameters into an init, or initializer, statement.  You can even include more than one init statement, if you want to create an instance of a class by going two separate routes. So for example, we could initialize the class with code that would only run for Mario and different code that might run only for Luigi…

So you can see at #1 and #2 we have two different init statements.  Both of which pass in a parameter of Int type which is named lives.  In both init statements we simply set a variable called livesLeft to that of lives. The livesLeft property will stick around as long as the class does, it won’t get automatically cleaned out from memory like the lives variable would. Reason being, the lives variable is only local to the init statement and when that finishes running, it won’t hold onto values it doesn’t need to.

So how do we create an instance of the MarioBrother class and specify which init “road to go down”? Like this…

Easy huh!

If you want to pass multiple parameters into an init statement, here’s an example…

Notice we comma separate the two parameters, and each have a colon separating the parameter name and it’s Type.

To create an instance with multiple parameters it would look like this…

Continue on to Part 9

 

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

0 Comments

Leave a reply

Check out our premium Swift and Sprite Kit Tutorial content!

Visit CartoonSmart.com