Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Object-Oriented Swift Class Inheritance Creating a Subclass

George Gregorczyk
George Gregorczyk
3,028 Points

I get an error that I can't override.

Sorry that you have to review this rookie code but could someone explain to me what I am doing wrong?

objects.swift
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 {
  let numberOfSeats: Int = 4
    override init(withDoors doors: Int, andWheels wheels: Int, withSeats seats: Int) {
      self.numberOfDoors = doors
      self.numberOfWheels = wheels
      self.numberOfSeats = seats
  }
}

let someCar = Car(withDoors: 4, andWheels: 2, withSeats)

1 Answer

Hey George - When you're trying to initialise properties that are in a subclass, you need to initialise them using super.init after your classes properties have been initialised.

I also noticed that the declaration of someCar on line 20 is missing a withSeats declaration and that you were initialising numberOfSeats with a hardcoded value in the class itself. I've attached the modified code below - seems to pass ok. Hope this helps!

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 {
  let numberOfSeats: Int

    init(withDoors doors: Int, andWheels wheels: Int, withSeats seats: Int) {
        self.numberOfSeats = seats
        super.init(withDoors: doors, andWheels: wheels)
    }
}

let someCar = Car(withDoors: 4, andWheels: 2, withSeats: 1)

Hi Thomas, thanks for your answers. Please make sure you post them as answers and not comments. This helps for to know which answers are helpful when the author of the question has the ability to mark them as "best answers". Cheers