Today we'll continue looking at initialization in Swift with Designated Initializers. Let's get started.
Swift's initialization system is made up of what are essentially a set of rules. We'll step through them here. Let's start with a class.
The first rule of Designated Initializers is that we need one. All classes must define (or inherit) at least one.
Ok, we've added one designated and one convenience initializer. Not too shabby. Now, let's use this base class.
Uh oh, what's going on here? Turns out it's the next rule. We're writing the designated initializer for Peakachew
. Designated initializers must call a designated initializer from their immediate superclass, not a convenience one like we tried to do here.
Well, we've fixed our first problem but we've hit the next rule. Designated initializers have to initialize all stored properties on their class before calling super.
Lastly, designated initializers must call their parent class's initializer before assigning a value to any properties they've inherited from it.
With that, we're done. We're now following all the rules:
class Monster {
var name: String
init(name: String) {
self.name = name
}
convenience init() {
self.init(name: "Nameless Monster")
}
}
class Peakachew : Monster {
var shouldFollow: Bool
init(shouldFollow: Bool) {
self.shouldFollow = shouldFollow
super.init(name: "Peakachew")
}
}
Whew!
More on initializing in Swift next time!