我只是想问一下,为什么这段代码打印出数量1,即使RecipeIngredient没有提供默认值:
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
}
}
let item = ShoppingListItem()
print(item.quantity)
答案 0 :(得分:1)
默认值由便捷初始值设定项RecipeIngredient
提供。
答案 1 :(得分:0)
ShoppingListItem()
是ShoppingListItem.init()
(继承自`Food)调用ShoppingListItem.init(name:)
(继承RecipeIngredient
)调用ShoppingListItem.init(name: name, quantity: 1)
(继承RecipeIngredient
)调用ShoppingListItem.init(name: String, quantity: Int)
(继承RecipeIngredient
),最终将数量设置为1 这是一些非常基本的调试。您应该真正研究如何使用Xcode debugger。