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 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)
Jhoan Arango
Jhoan Arango
14,575 Points

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