Learn iOS with Examples, Code Snippets and Video Tutorials

Day 4 – Learn Swift and Sprite Kit – Initialize with a Dictionary, For Loops and More Physics

Day 4 – Learn Swift and Sprite Kit – Initialize with a Dictionary, For Loops and More Physics
October 10, 2014 Justin

Day 4: Create multiple platforms for a typical game character to walk on

  • We create a Dictionary to pass data into a subclass of SKNode
  • We will place multiples instances of an SKSpriteNode inside of the SKNode class, each with an SKPhysicsBody.
  • We’ll end by creating a function to toggle between physics states of each platform.
Download the Xcode Project (updated for Swift 1.2)


Today was a good one with Swift. I haven’t lost much more hair than usual. Nails are short, but not gnawed-to-the-bone short. Let’s take a look at the first thing we tackled: creating a Dictionary to house data to pass as a parameter into the init statement of a custom subclass of SKNode.

This is in the didMoveToView function of the GameScene class.

Doesn’t that look pretty? We have a column of dictionary keys, each with a colon followed by their value. So for example, the key “ImageName” has a value of “platform“. If that looks confusing, imagine it organized like this…

Xcode Property List Example

That image shows a Property List with four properties of String type, just like the code. We won’t actually use a property list in this project, but essentially our groundData Dictionary is exactly the same as what you’re seeing in the image. As a side note, normally I would almost always create a property list to define data for game objects, but for our purposes learning early on, it’s worth doing it the old fashioned way. This gives you an idea though of how setting properties could define the data for an entire game, which is exactly how my iOS Starter Kit works (with some help from Tiled)

Let’s jump over to the init statement now of our new Object class.

Notice the parameter for the init statement is a Dictionary type and we’re specifying that the data to expect will be <String, String> for the keys and values. Back in the GameScene, when we created the groundData dictionary it was also set as [String: String] albeit with slightly different bracketing.

Once the data is passed in,  we’ll be referring to the dictionary as theDict. So to access the data stored for the “ImageName” Key we could write…

The constant image now equals platform, because that’s what the value of theDict[“ImageName”] was when it was passed in. This constant will be available to us throughout the rest of the init statement.

The Swift code to position the entire node doesn’t look that much different than it’s Objective C counterpart. For example….

To convert the data stored for the “Location” key, we need to use CGPointFromString( ).  If you noticed, the raw data was “{0,300}“. This conversion strips out those brackets and makes it so our CGPoint location stores 0 for the x value and 300 for it’s y value. Essentially we now have this…

So when we write…

…that will move the entire node (including any children) to a new location.


Adding Multiple SKSpriteNodes inside the SKNode

Immediately after setting the position, we’ll tackle adding a specific number of SKSpriteNodes based on the “PlaceMultiplesOnX” value in the dictionary.

At #1, we check to see if there actually is a non-nil value for the “PlaceMultiplesOnX” property. If it was nil, you’ll see in the video we simply create one instance of SKSpriteNode instead of multiples.

At #2 we go a rather not-so Swift way about converting a String value to an Int. With my still limited experience with Swift (hey, its only Day 4), I went with that two line conversion. I know I could have compressed it to one line (seen below), but visually I thought this looked even more insane to new users…

Basically, I create a String constant named multiples equal to the Dictionary data. That data is 10, but stored as a String, not an Int, which is why it needs converting. Then on the next line, I create a constant Int named amount  which equals the toInt()! conversion of multiples. The compiler felt I needed that exclamation point to force unwrapping the value of multiples (okay whatever you say).

At #3 we create a for loop using amount. Nothing particularly new or Swift-like about this. We’ll iterate through the loop the same number of times as whatever amount equals.

Our first order of business in each iteration is to create a new SKSpriteNode  named objectSprite and initialize it with the value of image!  (which if you remember is “platform”). Keep in mind, each iteration will create an objectSprite that can co-exist just fine with every other objectSprite. Adding one does not overwrite the other.  And even though these instances don’t have a .name property, which could give them a unique name, those name values could still be identical.  Swift doesn’t care. Sprite Kit doesn’t care either.

At #4 we’re positioning each instance at a unique location by multiplying the width of the objectSprite by the value of i (from the for loop). By working in a little math to both the x and y location, our platforms get added to the parent node like this…

Xcode and Swift Project Example Image

Guess I didn’t need 10 of them, huh.

At #5 we check to see if the dictionary key for “BodyType” is equal to “square“. If so, we give the objectSprite a physics body with a rectangular shape the same size as the objectSprite (which is the image size). Finally we set the .dynamic property to false. This way the platform is left out of the physics simulation. It’s body can still collide with things, but gravity won’t affect it and it won’t budge if other objects hit it.

Back in the GameScene class you can include this line in the didMoveToView statement…

This will allow you to see the physics bodies as outlines around each object when the game is run. Here’s what that looks like…

Show Physics Bodies in Swift

We have a lot more fun after this point in the video version of the tutorial, so if you want to learn more, give it a gander.


Move onto Day 5



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

Your email address will not be published. Required fields are marked *


Check out our premium Swift and Sprite Kit Tutorial content!

Visit CartoonSmart.com