Swift - Class Initializing Variables and Constants During Initialization

Introduction

The compiler automatically generates a default initializer if the properties are initialized to their default values.

Suppose you have the following class definition:

class Point {
    var x: Double
    var y : Double
    let width: Int
}

The preceding class definition will not compile, as the compiler cannot find the default values for the properties.

However, if you were to add an initializer that initializes the properties'values, this would compile:


class Point {
    var x : Double
    var y : Double
    let width : Int

     init() {
         x = 0.0
         y = 0.0
         width = 2
     }
}

Related Topic