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 trialSam Dale
6,136 PointsSwift 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
23,970 PointsAhh Got you, no that is not possible in Swift
Jeff McDivitt
23,970 PointsNot 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
6,136 PointsThanks 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".
Sam Dale
6,136 PointsSam Dale
6,136 PointsOkay. Thanks for the help!