Introducing initializers
You learned about initializers in the previous chapters, but let’s look at them again with your newfound knowledge of methods.
Initializers are special methods you can call to create a new instance. They omit the func keyword and even a name; instead they use, simply, init. An initializer can have parameters, but it doesn’t have to.
Right now, when you create a new instance of the SimpleDate structure, you have to specify a value for the month property:
let date = SimpleDate(month: "January")
You might find it more efficient to have a handy no-parameter initializer. This would create a new SimpleDate instance with a reasonable default value:
let date = SimpleDate() // Error!
While the compiler gives you an error now, you can provide the no-parameter initializer. By implementing init, you can create the simplest path to initialization with default values:
struct SimpleDate {
var month: String
init() {
month = "January"
}
func monthsUntilWinterBreak() -> Int {
return months.index(of: "December")! - months.index(of: month)!
}
}
Here’s what’s happening in this code:
- The init() definition requires neither the func keyword nor a name. You always use the name of the type to call an initializer.
- Like a function, an initializer must have a parameter list, even if it is empty.
- In the initializer, you assign values for all the stored properties of a structure.
- An initializer never returns a value. Its task is simply to initialize a new instance. Now you can use your simple initializer to create an instance:
let date = SimpleDate()
let month = date.month // January
let monthsLeft = date.monthsUntilWinterBreak() // 11
You can test a change to the value in the initializer:
init() {
month = "March"
}
The value of monthsUntilWinterBreak() will change accordingly:
let date = SimpleDate() // March
let monthsLeft = date.monthsUntilWinterBreak() // 9
As you think about the implementation here, a good user experience optimization would have the initializer use a default value based on today’s date.
In the future, you’ll be capable of retrieving the current date. Eventually you’ll use the Date class from the Foundation library to work with dates. Before you get carried away with all the power that these libraries provide, let’s continue implementing your own SimpleDate type from the ground, up.