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 trialRay Hiera
1,870 PointsDear Treehouse I find this rather complex and changed the code often It is not clear to me why it won't compile pls
class Vehicle { var numberOfDoors: Int var numberOfWheels: Int
init(withDoors doors: Int, andWheels wheels: Int) {
self.numberOfDoors = doors
self.numberOfWheels = wheels
}
}
// Enter your code below class Car: Vehicle { var numberOfSeats: Int
override init(withDoors doors: Int, andWheels wheels: Int) { self.numberOfSeats = 4
super.init (withDoors: doors, andWheels: wheels)
} }
let someCar = Car(withDoors: 4, andWheels: 4)
class Vehicle {
var numberOfDoors: Int
var numberOfWheels: Int
init(withDoors doors: Int, andWheels wheels: Int) {
self.numberOfDoors = doors
self.numberOfWheels = wheels
}
}
// Enter your code below
class Car: Vehicle {
var numberOfSeats: Int
override init(withDoors doors: Int, andWheels wheels: Int) {
self.numberOfSeats = 4
super.init (withDoors: doors, andWheels: wheels)
}
}
let someCar = Car(withDoors: 4, andWheels: 4)
1 Answer
Reed Carson
8,306 Pointsyou are close. I 'm really bad at class initializers, I had to check on it to get right.
class Car: Vehicle {
var numberOfSeats: Int = 4
init(doors: Int, wheels: Int, seats: Int) {
self.numberOfSeats = seats
super.init(withDoors: doors, andWheels: wheels)
}
}
let someCar = Car(doors: 2, wheels: 3, seats: 5)
you want to include all the variables in your override init, and then in the call to the super class init (super.init) you just pass in the values you get from the new init you wrote. The default value needs to be set when the variable is declared, not in the initializer, otherwise you would have no way to change it. The point of initializers is to make sure all constants and variables have a value when the class object is created. Since there is a default value for numberOfSeats, you dont actually need to include it in the initializer, unless you want to be able to set it to something else.
Ray Hiera
1,870 PointsRay Hiera
1,870 PointsThanks Reed for the advice