Initialization is one of the more trickier bits about Swift, especially if you are coming from something like Java or C#. In other languages, you think more along the lines of top-to-bottom. Meaning, you first construct all your parent objects before creating the child objects.
In Swift, safety comes first. The idea is that once you have all your properties set, you won’t be in a situation where they may be used (during initialization) when they aren’t ready to be used.
Take this example. Lets create a class called Person
class Person {
var name: String
init() {
self.name = "Bill"
print(speak())
}
func speak() -> String {
return "Hi, my name is \(name)"
}
}
As you can see, this simple class sets a property, then calls the speak method in the initializer. Notice that speak() actually references a property.
Now, lets examine a subclass:
class Student: Person {
var major: String
override init() {
self.major = "Computer Science"
super.init()
}
override func speak() -> String {
return "Hi, my name is \(name) and I study \(major)"
}
}
All we’re doing is adding another property but we’ve also overridden speak(). Now, when we create a new Student, the overridden speak() will be called.
By first setting the major property (this is, self.major = “Computer Science”), there will be a value present when speak() is called. Here is what it will look like in action:
var student = Student()
> Hi, my name is Bill and I study Computer Science
Give that a whirl in a playground to see what I mean.
I hope that helps!