iOS Object-Oriented Swift Class Inheritance Overriding Properties

Gene Bogdanovich
Gene Bogdanovich
10,213 Points

Why do we use 'self' when referring to the property defined in the base class?

Given this chunk of code:

class Enemy {
    var life: Int = 2
    let position: Point

    init(x: Int, y: Int) {
        self.position = Point(x: x, y: y)
    }

    func decreaseLife(by factor: Int) {
        life -= factor
    }
}


class SuperEnemy: Enemy {
    let isSuper: Bool = true

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

In the init override in the SuperEnemy class, why do we use self to refer to the life property? It's defined in the base class and it was my understanding that we only use self to access properties in the class that we're currently in. I would appreciate any help!

2 Answers

Greg Kaleka
Greg Kaleka
38,970 Points

Hi Gene,

Oziel has it right, but let me see if I can simplify it a bit:

When a class inherits from another class, it automatically gets all of its properties and methods. By having : Enemy in the class definition, SuperEnemy gets the life and position properties as its own properties. It also gets the decreaseLife method. This means that self.life is perfectly fine because it is a property of the SuperEnemy class.

Hope that helps!

Cheers :beers:

-Greg

Gene Bogdanovich
Gene Bogdanovich
10,213 Points

Thank you, Greg! That clears things up.

Greg Kaleka
Greg Kaleka
38,970 Points

Glad to hear it - happy coding!

Oziel Perez
Oziel Perez
61,319 Points

self does refer to the current class that you are in. But as far as I understand in swift, if the property isn't defined in the current class, but it is defined in the super class that it is derived from, then self will access that property. In contrast, if the property was written in the current class, then that property will override the super class property and self will have access to the property in the current class. This is helpful in case you want different classes to have different default values at initialization.

Disclaimer: I may have studied swift here, but I don't have much experience with the language, so my answer is based on experience with other OOP languages.