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
Sarah Chou
2,037 PointsWhen creating a subclass, do I have to initialize ?
I just did the code challenge for Swift - Creating a subclass. I initialized the subclass with override and it didn't pass but when I deleted it it passed. I thought initializing was compulsory for a class or a subclass ?
1 Answer
jcorum
71,830 PointsI find initialization can get a bit confusing, what with member wise initializers, default initializers, convenience initializers, inherited initializers, failable initializers, etc., and all the rules surrounding them.
But the bottom line is what's stated right at the beginning of Apple's documentation: "Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state." https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html
Another issue is that Treehouse's challenge editor sometimes is a bit quirky. You didn't give a link so I can't see exactly what it wanted, but sometimes even an extra space will defeat it.
Consider this code:
class Student {
private var name: String
init(name: String) {
self.name = name
}
}
class UnderGrad: Student {
}
var joe = UnderGrad(name: "Bob")
An initializer is not needed for UnderGrad because it introduces no new stored properties (instance variables in other languages). So the inherited initializer works fine. It meets the rule: every stored property (viz., name) is given a value.
Now consider this:
class Student {
private var name: String
init(name: String) {
self.name = name
}
}
class UnderGrad: Student {
private var grade: Int
init(name:String, grade: Int) {
self.grade = grade
super.init(name: name)
}
}
var joe = UnderGrad(name: "Bob", grade: 12)
Here, because UnderGrad introduces a new stored property grade, that property has to be initialized when an UnderGrad is created. Since the inherited initializer can't do it, UnderGrad has to have its own, which initializes grade and then calls the superclass's initializer to initialize name.
Hope this helps.
Sarah Chou
2,037 PointsSarah Chou
2,037 PointsThanks a lot it really helps !