Initializers in structures

Initializers ensure all properties are set before the instance is ready to use:

struct SimpleDate { var month: String var day: Int

init() {

month = "March" day = 1

}

}

If you tried to create an initializer without setting the day property, then the compiler would complain.

By creating even one custom initializer, you forgo the option to use the automatic memberwise initializer. Recall that the auto-generated memberwise initializer accepts all the properties in order as parameters, such as init(month:day:), for the Date structure. When you write a custom initializer, the compiler scraps the one created automatically.

So this code won’t work right now:

let date = SimpleDate(month: "February", day: 14) // Error!

Instead, you’ll have to define your own initializer with parameters:

init(month: String, day: Int) { self.month = month

self.day = day

}

In this code, you assign the incoming parameters to the properties of the structure. Notice how self is used to tell the compiler that you’re referring to the property rather than the local parameter.

This wasn’t necessary in the simple initializer:

init() {

month = "March" day = 1

}

In this code, there aren’t any parameters with the same names as the properties. Therefore, self isn’t necessary for the compiler to understand you’re referring to properties.

With the complex initializer in place, you can call the new initializer the same way you used to call the automatically generated initializer:

let date = SimpleDate(month: "February", day: 14) let month = date.month // February

let day = date.day // 14

results matching ""

    No results matching ""