gpt4 book ai didi

Swift 5 从 super 继承所需的 init

转载 作者:行者123 更新时间:2023-11-28 13:36:43 25 4
gpt4 key购买 nike

我正在学习 Swift apprentice 第 3 版。

本书快速跳过所需的初始化程序。

如果我有一个父类(super class):

class Animal {
let animalType: String

required init(animalType: String) {
self.animalType = animalType
}

convenience init(animal: Animal) {
self.init(animalType: animal.animalType)
}
}

然后子类化:

class WildAnimal: Animal {
let name: String

required init(animalType: String) {
name = ""
super.init(animalType: animalType)
}
}

我可以初始化子类的唯一方法是在所需的初始化中分配占位符值。即我必须输入 name = ""。

如果父类有必需的初始化,是否没有办法在初始化期间初始化子类参数?

最佳答案

你可以有多个初始化器。您还必须“覆盖”所需的父初始化程序。

class WildAnimal: Animal {
var name: String

required init(animalType: String) {
name = ""
super.init(animalType: animalType)
}

init(animalType: String, name: String) {
self.name = name
super.init(animalType: animalType)
}
}

强制子类定义 de required 初始化器是 required 的要点。

Write the required modifier before the definition of a class initializer to indicate that every subclass of the class must implement that initializer

Source

关于Swift 5 从 super 继承所需的 init,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56516275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com