Swift - Class Initializers and External Parameter Names

Introduction

An initializer does not have a name.

It is simply identified by the special name init; thus, the following initializers are valid:

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
    }

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

To differentiate between the second and third initializers is to specify the external parameter names when calling them.

To omit the external parameter name, prefix the parameter name with an underscore _


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
     }

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

In this case, you can call the second initializer without specifying the external parameter names:

var ptC = Point(7.0, 8.0)

Once the external parameter names are omitted, you can no longer call the second initializer with their external parameter names:

var ptC = Point(x:7.0, y:8.0)  //not allowed

You can continue to call the third initializer using the external parameter names:

var ptC = Point(y:8.0, x:7.0)

If you cannot prefix the parameter names in the third initializer with underscores:

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

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

Here, the compiler will generate an error message because it sees two initializers with the same parameter type.

Related Topic