1

I got a simple question that is not really trying to solve a problem but is asked out of curiosity.

Say this is whats in my GameScene.swift file:

import SpriteKit

class GameScene: SKScene {

     //Some global properties 
     let player = SKSpriteNode(imageNamed: "Player")
     var score = Int()

     override func didMoveToView(view: SKView) {

         //Way 1 (which I see most of the time)
         player.position.....
         score = 1

        //Way 2 (which I see sometimes)
        self.player.position...
        self.score = 1
}

What is the school of though behind self? I have seen some tutorials where people like to use self to be explicit. However most tutorials do not use self and I have even seen 1 tutorial where the guy said that unless self is explicitly needed (not sure what that means) you shouldn't use self.

Could someone please clear me up of wether I should use Way 1 or Way 2 and what the difference is? I appreciate any replies, thank you

Update

After coding for over 1 year now I actually prefer way 1 as member djeck has explained in his answer. I am only using self when I am required by the compiler. I think it makes code easier to read and it is also easier to identify when you have to use unowned self or weak self

2
  • 1
    It's a matter of personal reference. I like the second way because it is apparent at a glance that I'm modifying an instance variable. With the first way, you don't know if player is local to the func or belong to the class. Jun 1, 2015 at 20:46
  • 1
    Some similar questions with other languages: stackoverflow.com/questions/406053/… (Java) and stackoverflow.com/questions/2732045/… (C#). At the end of the day, it boils down to personal style. Don't overthink it! Jun 1, 2015 at 20:49

1 Answer 1

3

This is just a style preference and might not be suitable for stackoverflow's Q/A format but Ray Wenderlich has a style guide for this.

For conciseness, avoid using self since Swift does not require it to access an object's properties or invoke its methods.

Use self when required to differentiate between property names and arguments in initializers, and when referencing properties in closure expressions (as required by the compiler):

1

Not the answer you're looking for? Browse other questions tagged or ask your own question.