Introducing self
A structure definition is like a blueprint, whereas an instance is a real object. To access the value of an instance, you use the keyword self inside the structure. The method definition transforms into this:
// 1
func monthsUntilWinterBreak() -> Int {
// 2
return months.index(of: "December")! - months.index(of: self.month)!
}
Here’s what changed:
- Now there’s no parameter in the method definition.
- In the implementation, self replaces the old parameter name. You can now call the method without passing a parameter:
let monthsLeft = date.monthsUntilWinterBreak() // 2
While you can use self to access the properties and methods of the current instance, most of the time you don’t need to. In the previous example, you could have just said month instead of self.month. Most programmers use self only when it is required, for example, to disambiguate between a local variable and a property with the same name.