根据" Swift编程语言2.1",如果子类为其所有属性提供默认值,则子类自动继承其所有超类的指定初始化器和便利初始化器。因此,对于下面的代码,类ShoppingListItem
应该从其超类RecipeIngredient
继承三个初始化器,即
//1
convenience init() {
self.init(name: "[unnamed]")
}
//2
convenience init(name: String){
self.init(name: name, quantity: 1)
}
//3
init(name: String, quantity: Int){
self.quantity = quantity
super.init(name: name)
}
如果我想创建ShoppingListItem的实例,我会写
let ingredientThree = ShoppingListItem(name: "apple", quantity: 10)
这会调用init(name: String, quantity: Int){}
,但在此初始化程序中,会调用super.init(name: name)
,这就是我被卡住的地方。初始化过程达到super.init(name: name)
时会发生什么?它是否会调用ShoppingListItem
的超类init(name: String){}
初始化程序?或者不是吗?究竟发生了什么?请有人请向我解释一下吗?在此先感谢您的帮助!
实际代码:
class Food {
var name: String
init(name: String){
self.name = name
}
convenience init() {
self.init(name: "[unnamed]")
}
}
class RecipeIngredient: Food{
var quantity: Int
init(name: String, quantity: Int){
self.quantity = quantity
super.init(name: name)
}
override convenience init(name: String){
self.init(name: name, quantity: 1)
}
}
class ShoppingListItem: RecipeIngredient {
var purchased = false
var description: String {
var output = "\(quantity) X \(name)"
output += purchased ? " ✔" : " ✘"
return output
}
}
答案 0 :(得分:0)
我将您的代码放入游乐场并添加了一些打印件。以下是发生的事情:
顺便提一下,你问过它是否会调用ShoppingListItem的超类的init(name:String){}初始值。
答案是否定的。你用过的
let ingredientThree = RecipeIngredient(name: "apple", quantity: 10)
这与ShoppingListItem无关。
通常,如果您具有类继承Class1< - Class2< - Class3。然后你实例化Class2,然后Class 3永远不会发挥作用。
class Food {
var name: String
init(name: String){
print("Food.init")
self.name = name
}
convenience init() {
self.init(name: "[unnamed]")
}
}
class RecipeIngredient: Food{
var quantity: Int
init(name: String, quantity: Int){
print("RecipeIngredient.init(String, Int)")
self.quantity = quantity
super.init(name: name)
}
override convenience init(name: String){
self.init(name: name, quantity: 1)
}
}
class ShoppingListItem: RecipeIngredient {
var purchased = false
var description: String {
var output = "\(quantity) X \(name)"
output += purchased ? " ✔" : " ✘"
return output
}
}
let ingredientThree = RecipeIngredient(name: "apple", quantity: 10)