Learn iOS SpriteKit with Examples, Code Snippets and Video Tutorials

Day 1 – Learn Swift and Sprite Kit

Day 1 – Learn Swift and Sprite Kit
October 7, 2014 Justin

Well today I officially started learning Swift and Sprite Kit together. Keyword being “together” as I’ve been using Sprite Kit for a year now, and feel pretty darn comfortable with it.  I’ve programmed the Fantastic Worlds iOS Starter Kit, which is powerful game engine, all driven by setting simple properties and design levels in Tiled. So I’ve come a long way from where I was at this point almost exactly year ago with Sprite Kit, when I was just getting serious about learning it. Granted I had just written a book on Cocos2d (available from Focal Press and in the iBook Store), and Sprite Kit is like Cocos2d’s programming offspring, at times identical. Point is, Sprite Kit has always been a fun learning experience for me, partially because a lot of the kinks had been worked out with Cocos2d. Hopefully I can say the same about Swift in a year.

The language is, er… familiar but different. I come from an Actionscript 3 background, so at times Swift looks similar, with a lot of parenthesis instead of brackets (which I’ve grown to really love in Objective-C). And I know that programming languages are all fundamentally kind of the same, but until I get the swing of things with Swift, I also know that I’ll feel like slamming my head against the wall. When I make a mistake in Sprite Kit (with Obj-C), I usually figure out pretty quick where I messed up. My logic was wrong, or I just made a typo. Those errors still apply when learning a new language but  the most frustrating mistake is simply trying to do something that just isn’t done that way now!

And here, on Day 1 of my adventures with Swift, I’ve run into exactly that, quite a few times. I plan on documenting my day-by-day progress with some fun, free videos.  And speaking of,  here’s the first one…

And if you don’t feel like watching the video-blogged version of today’s events, here’s what it boils down to.

Day 1’s Big Notes. 

  • You don’t have to import in your other classes in Swift (ah-ha, very interesting).
  • Declaring variables as optionals seems to be something we’ll be doing a lot

I started things off today by creating my own class to test with the Swift/Sprite Kit starting project. That project creates a local SKSpriteNode (a rotating spaceship) every time you tap the screen. Instead I wanted to create and declare a class I could access in any function. So let’s start by looking at the class I created.

I went to File > New > File… and picked Swift File and named it Destroyer  (so the full file name ended up being Destroyer.swift)

New Swift File

Here’s what I entered into my class…

It’s a subclass of SKSpriteNode and does about as little as possible. The highlighted lines are the important part. This will initialize the class by passing in a String value which will be used to set the texture of the sprite node (the string should match one of the asset names in the Images.xcassets catalog). Ultimately I’m just showing the image. That’s it.

Now in the GameScene.swift file, I declared an instance variable of the Destroyer class (on line 8) then cleared out what was previously in the didMoveToView function, and replaced it with what’s below…

So now destroyerNode is declared as an optional variable to use in any of the functions in the class (including the didMoveToView function). The ? after the class name means it is optional, or basically that it can be nil for now, and could be for a while. But the didMoveToView statement very quickly makes it not nil, by initializing it with the imageNamed parameter.  After that we set the position and like every good node, we add it to the scene with the addChild function (once this happens we can actually see the node when the app runs).

What’s up with the exclamation point though?  Yeah that was news to me. After I initialized destroyerNode, I had to write destroyerNode! instead. Well, this is what’s called forced unwrapping. Again, news to me. But because our destroyerNode was declared as optional, we’re essentially committing this variable to now having a value. Or else. From what I’m reading the app would crash if destroyerNode did not have a value and we attempted to unwrap a value from it. Which makes sense. What would we be adding in the addChild line if destroyerNode didn’t really exist.

And did you notice we didn’t have to import in that Destroyer class at all. Convenient right.

The video goes on about a few more things I ran into on Day 1, but I won’t make you read much more for today. Hopefully this is just enough to keep you interested for tomorrow!

Ready For Day 2
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

5 Comments

  1. Grant Christie 3 years ago

    I am going to try and learn with you.

    We can use Swift’s syntax sugar ? and declare variables that can hold s.t. of it defined type or a nil. By adding a ? immediately after the data type you tell the compiler that the variable might contain a number or not. Does this mean during runtime, if we plan to turn objects into nil, it makes it a good idea to declare the Destroyer this way? Optional constants – you can set their value only once and therefore you would be able to say whether their value will be nil or not.

    var height: Int? = 180

    is actually equivalent to:

    var height: Optional = Optional(180)

    When you put a ! behind the property name you tell the compiler I don’t care that this property is optional, I know that when this code executes there always will be a value store so treat this Optional like a normal datatype. So, use ! only if you are 101% sure that this is safe. Or use a syntactical construct called optional binding.

    “if let” is a special structure in Swift that allows you to check if an Optional holds a value, and in case it does – do something with the unwrapped value. Let’s have a look:

    if let temperature = currentTemperature() {
      println(“The temperature is \(temperature)”)
    } else {
      println(“Unable to obtain current temperature”)
    }
    The if let structure checks if there’s a value stored and takes that value and stores its value in your constant constant.

    I am not sure yet how this is done for and object = or if it is done. I have learnt you You can cast an Optional property by using as?

    Justin, in safe programming should I check to see if the destroyer is class is not nil first before trying to instantiate it? Would there be a” if let” way of doing this?

    • Author
      Justin 3 years ago

      Yes, the ? vs ! thing seems like it will be what * pointers are in Objective C. That thing that new users will always have to second guess whether they need or not. I’m getting the hang of it though.

      About your question, that seems like a case where you would just test if it is nil and if so, then initialize it. The short hand “if let” is better for casting an object. I did a little of that in the Day 5 video. Quite nice

      I wouldn’t worry too much about safety for now. I know that doesn’t sound like the smart thing to say, but it seems like a lot of the important safety checking involves optional chaining (look that up in the Sprite Kit Programming Guide). Kind of like, if this is optional thing has an optional property, do this, and if not, don’t worry about it.

      Glad to have ya learning here!

  2. Grant Christie 3 years ago

    I have purchased a lot of your products and I find you are an amazing quality teacher who is very easy to listen to. I have learnt so much from your various courses. I would not have been able to get Apps on the store as easily without your courses. I found your site in 2001 – AS3 mainly then from memory. So a plug for anyone interested in Art for their games or training – go to Cartoonsmart. You won’t be disappointed. There really is no better value in my view.

    • Author
      Justin 3 years ago

      Thanks for the plug Grant! I definitely recognized your name last night. As you can guess I’ve got some “premium” Swift tutorials in the works for the main site. I’m digging this new blog though. Thanks!

  3. Nathan 3 years ago

    Justin,

    I wish I would have looked at this sooner! I’ve been pulling my HAIR out since the first Beta! Plus trying to look at others online and this is by far the BEST and easiest to follow! I as well have purchased things from you and am trying to buy more art.

    Keep up these great videos!

Leave a reply

Check out our premium Swift and Sprite Kit Tutorial content!

Visit CartoonSmart.com