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

Alexander Hansson
Alexander Hansson
2,083 Points

I don't understand how super.init works and why we use it. Could someone give me a hint or an explanation?

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) {
    super.init(withDoors: doors, andWheels: wheels)
    numberOfSeats = 4
}

}

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

    override init(withDoors doors: Int, andWheels wheels: Int) {
        super.init(withDoors: doors, andWheels: wheels)
        numberOfSeats = 4
    }

}

1 Answer

So basically classes, structures and enums all have initializers when implementing different values. In this case it is a class. The values in the method need to get initialized either early or later. (example: let numberOfDoors = 4//early). If you don't want to do this early you use an initializer for those values you haven't set in the variable/constant so you later can (for example) make an instance and assign the values. I guess you already know what a super class is in general. The reason for using super.init is to initialize the values you had in the first class since you are inheriting. If don't really know if this explanation answered your question but I hope that you figured it out. Make sure to watch the video again and check out youtube tutorials on superclasses. This can help alot.

class Vehicle { var numberOfDoors: Int var numberOfWheels: Int

init(withDoors doors: Int, andWheels wheels: Int) {
    self.numberOfDoors = doors
    self.numberOfWheels = wheels
}

}

class Carr: Vehicle { let numberOfSeats: Int

override init(withDoors doors: Int, andWheels wheels: Int) {
    self.numberOfSeats = 4
    super.init(withDoors: doors, andWheels: wheels)

} }

As you can see we override the initializers in the class vehicle. Then we set the numberOfSeats to being 4.