【发布时间】:2018-01-18 09:20:55
【问题描述】:
假设我有一个类 Dog 声明如下:
class Dog {
let variable1: String
let variable2: Int
init(variable1: String, variable2: Int) {
self.variable1 = variable1
self.variable2 = variable2
}
}
而ChowChow是Dog的子类,特意声明为空,如下:
class ChowChow: Dog {}
现在假设我希望向子类ChowChow 添加一个初始化程序。
我的问题是:为子类ChowChow 使用便利初始化程序之间有什么区别(如果有的话):
class ChowChow: Dog {
convenience init() {
self.init(variable1: "value1", variable2: 2)
}
}
和子类ChowChow的指定初始化器?:
class ChowChow: Dog {
init() {
super.init(variable1: "value1", variable2: 2)
}
}
使用以下测试,我可以看到两种实现的结果都是相同的:
let chowchow = ChowChow()
print(chowchow.variable1) // Prints "value1"
print(chowchow.variable2) // Prints "2"
提前感谢您的启发!
【问题讨论】:
标签: swift