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

Alex Kuo
Alex Kuo
7,889 Points

Code Question About Convenience Init in the Course

Hi, buddies,

I am curious about the following code from this course :

class Car: Vehicle { let numberOfDoors: Int

init(name: String, numberOfDoors: Int) self.numberOfDoors = numberOfDoors super.init(name:name)

convenience override init(name:String){ self.init(name:name,numberOfDoors:4)

convenience init(){ self.init(name:"Unnamed") }

}

}

In the last convenience init, why we do not have to specify the parameter "numberOfDoors" ? What is the "self.init" in the last convenience init ? The designated one or the convenience one preceeding the last one ?

1 Answer

Charles Kenney
Charles Kenney
15,604 Points

Good question. Convenience initializers, by design do not take all the base initializer's parameters. This is exactly why they are called convenience initializers. Their purpose is to support a specific pattern / use case of initialization with a given object, and therefore come with certain predefined properties.

With this example, our car class has the stored property 'numberOfDoors'. Because most cars have 4 doors, we can write a convenient supporting initializer, to call the designated initializer (self.init) and automatically pass 4 for the numberOfDoors parameter. Now when we want to create a car object resembling a common 4-door car, all we have to do is pass the parameter for the name. And just like that, we're writing more efficient code.

I recommend reading the initialization section of the Swift 3.1 docs.

Hope this answers your question, -Charles