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!

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 2.0 Class Inheritance Creating a Subclass

Kevin Gutowski
Kevin Gutowski
4,082 Points

When to initialize superClass properties and when to initialize self properties?

So I wanted to take the exercise a step further and make the numberOfSeats a variable and set it to a default of 4 seats. So I go about making my subclass like this.

class Car: Vehicle { var numberOfSeats: Int

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



Which seems to work. The only problem is that I originally had the two lines within the initializer flipped and Xcode was giving me an error saying "Property 'self.numberOfSeats' not initialized at super.init call." I don't understand why this works. I though you need to have super.init called first before self.property. Can someone explain why self.numberOfSeats needs to be initialized before the super?

Eric Hodgins
Eric Hodgins
29,207 Points

Check out this stackoverflow post. It might help explain why.


For the most part I think it's Swift's compiler performing safety checks to make sure nothing funny happens when things are initialized.

1 Answer

Digvijay Jaiswal
Digvijay Jaiswal
5,565 Points

Kevin, according to the rule of thumb, one need to initialize the base class first then the super class that's why.