Introduction

When you create an instance of a class using a pair of empty parentheses, you are calling its default initializer:

var ptA = Point()

The compiler can only generate the default initializer if all the properties within the class have default values.

The compiler automatically generates the default initializer; there is no need for you to define it.

To initialize certain properties to specific values, define an initializer using the special name init:

class Point {
    var x = 0.0
    var y = 0.0
    let width = 2
    lazy var pointMath = PointMath()

    init() {
         x = 5.0
         y = 5.0
    }
}

Initializers in Swift do not return a value.

The init() initializer is automatically called when you create an instance of a class using a pair of empty parentheses:

var ptB = Point ()
print(ptB.x)           //5.0
print(ptB.y)           //5.0
print(ptB.width)       //2

When you create an instance of the Point , the value of both x and y is set to 5.

You can create parameterized initializers by accepting arguments through the initializers.

The following example shows another initializer with two parameters:

class Point {
    var x = 0.0
    var y = 0.0
    let width = 2
    lazy var pointMath = PointMath()

    init() {
        x = 5.0
        y = 5.0
    }

     init(x:Double, y:Double) {
         self.x = x
         self.y = y
     }
}

When you create an instance of the class, you can call the initializer by passing it two arguments:

var ptC = Point(x:7.0, y:8.0)
print(ptC.x)           //7.0
print(ptC.y)           //8.0
print(ptC.width)       //2

Related Topic