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

Sam Dale
Sam Dale
6,136 Points

Swift Subclass Additional Parameters

Hi there. I noticed one interesting comment Pasan slipped in about Subclasses in the Inheritance course. He said that subclass inits have to have the same parameters as the superclass. The first time I learned about Inheritance was in Java and it seems strange to me that you can't throw in extra arguments for sublcasses.

This isn't a deal-breaker, I just thought it odd that code like this doesn't work:

struct Point {
    let x: Int
    let y: Int
}


// Enemies
// Superclass/Parent
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
    }
}

// SuperEnemy Inherits from Enemy (has everything Enemy has)
// Subclass
class SuperEnemy: Enemy {
    let isSuper: Bool = true

    // overriding method:
    override init(x: Int, y: Int, name: String) {
        super.init(x: x, y: y)
        self.life = 50
    }
}

let enemy = Enemy(x: 1, y: 1)
let superEnemy = SuperEnemy(x: 1, y: 1)
superEnemy.life

So is this true or is there a way that Apple wants you to get around this? Thanks!

2 Answers

Jeff McDivitt
Jeff McDivitt
23,970 Points

Ahh Got you, no that is not possible in Swift

Sam Dale
Sam Dale
6,136 Points

Okay. Thanks for the help!

Jeff McDivitt
Jeff McDivitt
23,970 Points

Not sure if this is what you are looking for

class SuperEnemy: Enemy {
    let isSuper: Bool = true

    // overriding method:

        var name: String
    override init(x: Int, y: Int) {
        self.name = "Super Enemy"
        super.init(x: x, y: y)
        self.life = 50
    }
}

let enemy = Enemy(x: 1, y: 1)
let superEnemy = SuperEnemy(x: 1, y: 1)
superEnemy.life
superEnemy.name
Sam Dale
Sam Dale
6,136 Points

Thanks for the response.

What I was actually looking for was if you could do something where "Enemies" don't have names, but "Super Enemies" have names unique to each instance such as Greg or Charles and this name would be passed in while instantiating the "Super Enemy".