Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Object-Oriented Swift 3: Overriding Properties - Why use "self" instead of "var"

The code below uses "self.life" to define the life variable in the Sub Class, but why can't we just use "var life = 50" instead? I guess I'm just not clear on when to use "self" vs using "var" within the Sub Classes.

class SuperEnemy: Enemy {
    let isSuper: Bool = true

    override init (x: Int, y: Int) { 
        super.init(x: x, y: y)
        self.life = 50
    }
}

2 Answers

in OOP, self (or this in some languages) refers to the instance or object, in this case a super enemy. the overridden init method sets the life value for each super enemy created to 50, which i assume is higher than regular enemies. var is used to declare variables and here i would assume it has been used in the enemy class to declare the life variable, and once declared there is no need to use the var keyword for that variable anymore. since we are inheriting from the enemy class, life does not need to be declared again and can be referred to in each object with the self keyword.

That makes complete sense! Since we've already created the "life" variable, we can reference it in our SubClasses using "self".

Thank you!