Initialization

Initialization is the process of preparing an instance of a class, structure, or enumeration for use.

Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created.

Properties of optional type are automatically initialized with a value of nil.

You can initialize properties in declaration or in the special method init() called initializer (constructor in other languages).

Swift provides a default initializer for any structure or class that provides default values for all of its properties and doesn’t provide at least one initializer itself.

struct Fahrenheit {
    var temperature = 32.0
}

struct Fahrenheit {
    var temperature: Double
    init() {
        temperature = 32.0
    }
}

var f = Fahrenheit()

You can define several initializers.

struct Celsius {
    var temperatureInCelsius: Double
    init(fromFahrenheit fahrenheit: Double) {
        temperatureInCelsius = (fahrenheit - 32.0) / 1.8
    }
    init(fromKelvin kelvin: Double) {
        temperatureInCelsius = kelvin - 273.15
    }
}

Structure types automatically receive a memberwise initializer if they don’t define any of their own custom initializers. Unlike a default initializer, the structure receives a memberwise initializer even if it has stored properties that don’t have default values.

struct Size {
    var width = 0.0, height = 0.0
}
let twoByTwo = Size(width: 2.0, height: 2.0)

You can define a convinient initializer, that calls other initializer.

class Food {
    var name: String
    init(name: String) {
        self.name = name
    }
    convenience init() {
        self.init(name: "[Unnamed]")
    }
}