Initializing Phase 1 and Phase 2 in Swift

This is a copy of the 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 completed.

The designated superclass initializer now has the ability to configure the instance further (although this is not necessary).

After the initialization of the superclass is complete, the subclasses assigned to the initializer can perform additional configuration (although again this is not necessary).

Thus, basically Phase 1 ensures that all properties have a value and assign it that value. In step 2, these properties are additionally configured. And this further setup really disappoints me, because I can’t come up with any example that uses the additional setup. Can you give me a simple example of this initialization behavior or give an additional explanation of steps 1 and 2? Thanks

+4
source share
4 answers

Given the 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
    }
}

Bar(), super.init(), , Foo. , Foo , Foo. a = 1 Foo.

, 2, Bar super.init(). " " , . b = 2 c = 3.

let x = Bar()
x.a // 1
x.b // 2
x.c // 3
+8

, UIView, . self.frame 1 ( [super initWithFrame:frame], self.backgroundColor initWithFrame:, 2.

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame]; <- Phase 1

    if (self) {
        //Phase 2
        self.backgroundColor = [UIColor redColor];
    }

    return self;
}

Objective-C, Siwft, .

+1

. 1 . . , .

1 , . .

1 , .

, , init, 2.

, , 2. :

+1
source

My example is for understanding the first phase and second phase in Swift Innitialization.

class A {
  var a: Int
  var b: Int
  init() {
     // This is phare 1
     a = 1
     b = 2
  }
}

 class B: A {
   var c: Character
   var d: Double
   var e: String
   overide init() {
      // This is phare 1
      c = ""
      d = 0.0
      e = ""
      This is Phase 2
      d = 10
      e = "abc"
  }
 }
+1
source

All Articles