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 Class Inheritance Overriding Properties

Changing property with SubClass

When changing the life property within the SubClass of SuperEnemy, we are told to make the change within the initializer:

class SuperEnemy: Enemy {

    let isSuper: Bool = true

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

Is there any reason why we cannot just simply restate the var of life in the class with the new value of 50?

class SuperEnemy: Enemy {

    let isSuper: Bool = true
    var life: Int = 50

    override init(x: Int, y: Int) {
        super.init(x: x, y: y)
    }

I see it throws an error, but curious as to why.

1 Answer

Jhoan Arango
Jhoan Arango
14,575 Points

Hello,

Since the super class, or base class already has this property, the subclass is inheriting this property by default. In order for you to create your own life property ( which in this case would be pointless ) you'd have to override it.

override var life: Int = 50

Hope this helps

Makes sense. Thanks Jhoan!