Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phase 1 and Phase 2 initialization in Swift

This is copy from Apple Swift documentation:

As soon as all properties of the superclass have an initial value, its memory is considered fully initialized, and Phase 1 is complete.

The superclass’s designated initializer now has an opportunity to customize the instance further (although it does not have to).

Once the superclass’s designated initializer is finished, the subclass’s designated initializer can perform additional customization (although again, it does not have to).

So basically the Phase 1 makes sure that all properties have a value and assigns that value to them. In Phase 2 these properties are further customized. And that further customization really frustrates me because I can't think of a single example in which further customazation is used. Can you give me a simple example of this initialization behaviour or provide additional explanation of Phase 1 and 2? Thanks

like image 423
potato Avatar asked Mar 24 '15 10:03

potato


People also ask

How many initializer are there in Swift What is 2 phase initialization in Swift?

Here, the superclass has a single designated initializer and two convenience initializers. One convenience initializer calls another convenience initializer, which in turn calls the single designated initializer.

What is initialization in Swift?

Swift init() Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready for use.


1 Answers

Given 2 classes Foo and Bar where Bar is a subclass of Foo:

class Foo {
    var a: Int?
    var b: Int?

    init() {
        a = 1
    }
}

class Bar: Foo {
    var c: Int?

    override init() {
        super.init() // Phase 1

        // Phase 2: Additional customizations
        b = 2
        c = 3
    }
}

When you call Bar() it calls super.init() which the first line is to initialize the superclass which is Foo. So once Foo's properties are initialized completely, they can be set in Foo's initializer. This is represented by the a = 1 in the Foo initializer.

Once that is complete, phase 2 begins which is continuing the initialization of Bar following the super.init() line. This is where you can "perform additional customizations" either on the instance of bar or on its superclass. This is represented by b = 2 and c = 3.

let x = Bar()
x.a // 1
x.b // 2
x.c // 3
like image 144
Ian Avatar answered Oct 24 '22 21:10

Ian