Sobes.tech
Junior — Middle

In what order do constructors and initializers execute when creating an instance of a class?

sobes.tech AI

Answer from AI

When creating an instance of a class in iOS (for example, in Swift), the execution order is as follows:

  1. First, the initializers of all properties declared in the class are executed (if they have default values).
  2. Then, the initializer (constructor) of the class itself is called.
  3. If the class is inherited, the initializers of the superclass are called first, followed by those of the subclass.

Example in Swift:

class Parent {
    var name: String = "Parent"
    init() {
        print("Parent init")
    }
}

class Child: Parent {
    var age: Int = 10
    override init() {
        super.init() // first, the superclass initializer
        print("Child init")
    }
}

let c = Child()
// Output:
// Parent init
// Child init

Thus, properties are initialized first, then the superclass initializer is called, followed by the subclass initializer.

In what order do constructors and initializers… - sobes.tech