Swift中的阶段1和阶段2初始化 [英] Phase 1 and Phase 2 initialization in Swift

查看:83
本文介绍了Swift中的阶段1和阶段2初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Apple Swift文档的副本:

This is copy from Apple Swift documentation:

父类的所有属性都具有初始值后, 它的内存被认为已完全初始化,并且阶段1已完成.

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).

因此,基本上,第一阶段确保所有属性都有一个值,并将该值分配给它们.在阶段2中,将进一步定制这些属性.进一步的定制确实让我感到沮丧,因为我想不出一个使用进一步的定制化的例子.您能否给我一个有关此初始化行为的简单示例,或者提供有关阶段1和阶段2的其他说明?谢谢

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

推荐答案

给出2个类Foo和Bar,其中Bar是Foo的子类:

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

当您调用Bar()时,它会调用super.init(),其第一行是初始化超类Foo.因此,一旦Foo的属性被完全初始化,就可以在Foo的初始化程序中对其进行设置.这由Foo初始化程序中的a = 1表示.

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.

完成后,阶段2开始,该阶段继续super.init()行之后的Bar初始化.在这里,您可以在bar实例或其超类上执行其他自定义".这由b = 2c = 3表示.

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

这篇关于Swift中的阶段1和阶段2初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆