我该如何处理这个初始值设定项?

How do I handle this initializer?

创建一个名为 Parent 的 class 和一个 title 属性 并为您的 [=24] 编写一个 initdeinit 方法=].

写一个名为 Child 的子class。

我的问题是将其放入代码中(调用 super.init(title:) 并传递 title 参数。

class Parent {
    let title: String

    init(title: String){
        self.title = title
        print("\(title) is initialized")
    }

    deinit {
        print("\(title) is being deinitialized.")
    }
}

class Child: Parent {
    let subtitle: String
    init(subtitle: String){
        self.subtitle = subtitle
        // i'm supposed to call a super.init, how

        print("\(subtitle) is initialized")
    }

    deinit {
        print("\(subtitle) is being deinitialized.")
    }
}

为您的 Child 创建一个 titlesubtitle 的初始化器,然后在 Child 的初始化器中调用 super.init(title: title)

class Child: Parent {
    let subtitle: String
    init(title: String, subtitle: String){
        self.subtitle = subtitle
        super.init(title: title)

        print("\(subtitle) is initialized")
    }

    deinit {
        print("\(subtitle) is being deinitialized.")
    }
}

然后,如果您创建一个 Child 对象并将其分配给一个 Optional Child(即 Child?),您将同时看到已初始化 条消息:

var child: Child? = Child(title: "Star Wars: Episode VI", subtitle: "Return of the Jedi")

Star Wars: Episode VI is initialized
Return of the Jedi is initialized

然后如果您将 nil 分配给您的变量,您将看到两个 deinitialized 消息:

child = nil

Return of the Jedi is being deinitialized.
Star Wars: Episode VI is being deinitialized.

实际上我没有尝试过,但我认为它可以这样工作。让我知道它是否有效。

class Child: Parent {
    let subtitle: String

    override init(title: String, subtitle:String) {
        self.subtitle = subtitle
        super.init(title)
    }
}