1. Overview
Creates an instance of a class, struct, and enumeration by defining the constructor initializers . Unlike Objective-c's initializers, initializers in Swift does not have a return value.
An instance of class types can also implement the destructor Deinitializerto clean up before the class is freed.
2. Initialization of the stored Properties (Setting Initial Values for stored properties)
The stored properties of classes and structs must have appropriate values when their instances are created.
You can initialize them in the constructor, or you can set default values for them at the time of definition.
Note: The property monitor will not be called when initializing the stored attribute, either by using the default value initialization or by invoking the constructor initialization.
2.1 Constructor initializers
A constructor is a init
method with no parameters defined by a keyword that is used to create an instance of a type:
init () { // perform some initializationhere }
Such as:
struct Fahrenheit { // Fahrenheit temp varDouble init () { 32.0 } } var f = Fahrenheit () println(" the default temperature is \ (f.temperature) °fahrenheit") // prints "The default temperature is 32.0°fahrenheit"
2.2 Default Parameter value defaults property values
When a parameter always has an identical initialization value, it is better to use the default parameter value than to initialize it in the constructor. Of course their results are the same
struct Fahrenheit { var32.0 }
3. Custom initialization method Customizing initialization
The following example defines the two initializers of a struct Celsius
for initializing different ranges of temperatures:
13. Initialize Initialization