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 2.0 Class Inheritance Overriding Methods

What is 'self' referring to inside the overridden init method?

In previous lessons, we learnt that the 'self' property refers to the current instance within its own instance methods. So, if we use the 'self' property in the overridden init such as:

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

Is the 'self' property referring to the instance of the subclass or the superclass?

2 Answers

Abdullah Althobetey
Abdullah Althobetey
18,216 Points

self always refers to the current instance being used. In your example, self refers to the subclass, where super refers to the super class.

Also I'm not sure if the property 'life' in your code is declared in the subclass or in the superclass. If it is in the subclass, you need to call super.init() before you initialize the variables of the subclass (unless a variable is optional). If it is in the superclass, then it is may be an optional or initialize to a default value in your init() method of the super class, so in this case, you are simply reassign a value to the property 'life'

Self is used to access the stored properties of the Super Class