[Swift Game] Day 1 - Code Exercise Solution


#1

Please share your code or answers with your classmates for the Day 1 Code Exercise and related Notebook Activity questions.

Share your notes or sketches

Concept

Rough Sketch + Gameplay

Game Screens

Share code using

Solution

Only use code or watch video solution if you’re unsure how to solve or get stuck. It’s better to attempt writing the code first.


#2

Why the default XCode game is adding Spaceship using self.addChild(sprite) in line 38, while in day 2 lecture code Paul is adding without ‘self’ like addChild(background) or addChild(playerShip) ?
Also please if anyone have a good and clear explanation why and when we need to use SELF, please share it!


#3

In Swift you do not need to use self, except in a few edge cases.

Generally I prefer not to write it, because I find it distracting and unnecessary to the logic of the app. (It is required in Objective-C, but not Swift).

  1. The only place it is required is when writing a block of code, that gets passed to a function (animation block or SKAction block).
  2. Another place you may see it is when you want to use the same name in a method as a variable in a class. Usually this is some kind of setter method to pass data to your code file.

Otherwise you can leave it out. Different programmers have different programming styles. That’s why the default Xcode game project has the code written a certain way.

The code I present is in a code style that I feel is good for Swift programmers to adopt for clarity.