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
Antony Gabagul
9,351 PointsWhy do we always initialize, and is it necessary?
Hello. I've been searching through Apple Swift 2.2 documentation, and I've seen that they don't use initialization and overriding of initialization in their examples for Inheritance and Overriding.
1 Answer
jcorum
71,830 PointsThe first example in the Swift documentation you provide a link for creates a base class, Vehicle, with two stored properties: currentSpeed and description.
class Vehicle {
var currentSpeed = 0.0
var description: String {
return "traveling at \(currentSpeed) miles per hour"
}
func makeNoise() {
// do nothing - an arbitrary vehicle doesn't necessarily make a noise
}
}
Next, a subclass is created:
class Bicycle: Vehicle {
var hasBasket = false
}
And a Bicycle object:
let bicycle = Bicycle()
Whose currentSpeed is updated as follows:
bicycle.currentSpeed = 15.0
Your question is whether there is any initialization going on here. Answer: yes. When the bicycle object is created its stored properties (instance variables in other languages) are initialized. Apple defines initialization, in part, as the process of making sure that every stored property is given an initial value; something that has to happen before an object can be created. When the bicycle object is created it inherits the stored properties of the Vehicle class, and uses the initializer of that superclass to give them their initial values. In particular, currentSpeed is set to 0.0.
In this case the initializer is the default initializer. If you were to write it out, it would look something like this:
init(currentSpeed: Double) {
self.currentSpeed = currentSpeed
}
But since it's the default initializer it doesn't need to be added to the Vehicle class. It's already there, behind the scenes, as it were.
So to answer your initial question, we initialize because Swift requires it. "All stored properties must have initial values. " And yes, it is necessary. They do use initialization in the Inheritance documentation, they just don't illustrate it or talk about it, probably because Initialization is the next chapter.
Happy coding!