简体   繁体   English

为什么 Swift 需要在 super.init() 之前初始化子类的属性

[英]Why does Swift need to initialized subclass's property before super.init()

问题来了,我想知道 init 是如何工作的,子类的属性存储在哪里

Here's an example, to exemplify one of the reasons, let's say you have the following class definitions:这是一个示例,为了说明原因之一,假设您有以下类定义:

class Base {
    init() {
        sayHello()
    }

    func sayHello() {
        print("Hello from base")
    }
}

class Derived: Base {
    let name: String

    override init() {
        // no initialization of own properties, just call super()
        super.init()
    }

    override func sayHello() {
        print("Hello from \(name)")
    }
}

Basically, the initialized of the base class calls sayHello , a method which is overwritten in the child class.基本上,基类的初始化调用sayHello ,该方法在子类中被覆盖。 Now, calling super.init() results in the overriden method being called, which in turn needs to use the name property, which is not initialized a this point.现在,调用super.init()导致调用 overriden 方法,该方法又需要使用name属性,该属性未在 this 点初始化。

The requirement to have all subclass storage initialized before calling super.init is to ensure object validity before any possible actions are called on it.在调用super.init之前初始化所有子类存储的要求是在对其调用任何可能的操作之前确保对象有效性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM