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

bogdan barbulescu
PLUS
bogdan barbulescu
Courses Plus Student 232 Points

Why my subclass does not inherit the default initializer from the SuperClass?

//class turtle

class myTurtle  {

var numberOfTurtles = 7
}
let myturtle = myTurtle()



class SmilyTurtle: myTurtle {

var funnyTurtle = 4
var happyTurtle:Int
}


let smilyturtle = SmilyTurtle()
print(smilyturtle.numberOfTurtles)

2 Answers

The problem is that you have an uninitialized stored property in SmilyTurtle: happyTurtle

class SmilyTurtle: myTurtle {

    var funnyTurtle = 4
    var happyTurtle:Int  //you can't leave happyTurtle uninitialized
}

And the default initializer for myTurtle wouldn't be any help, as there is no happyTurtle property in myTurtle.

Here's an excerpt from the Apple documentation (I added the emphasis):


As mentioned above, subclasses do not inherit their superclass initializers by default. However, superclass initializers are automatically inherited if certain conditions are met. In practice, this means that you do not need to write initializer overrides in many common scenarios, and can inherit your superclass initializers with minimal effort whenever it is safe to do so.

Assuming that you provide default values for any new properties you introduce in a subclass, the following two rules apply:

Rule 1 If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.

Rule 2 If your subclass provides an implementation of all of its superclass designated initializers—either by inheriting them as per rule 1, or by providing a custom implementation as part of its definition—then it automatically inherits all of the superclass convenience initializers.


https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-ID203

bogdan barbulescu
PLUS
bogdan barbulescu
Courses Plus Student 232 Points

I had missed the part where it reads that: "provide default values for any new properties you introduce in a subclass"

Thank you