根据我的理解,方便初始化器是init
缺少具有默认或硬编码值的属性,或者给予实现任何灵活数量的参数并满足 init规则,即所有属性都应该是在创建对象之前初始化。
像:
class A {
var name:String;
var salary:Float;
init(name:String,salary:Float) {
self.name = name;
self.salary = salary;
}
convenience init(name:String) {
self.init(name:name , salary:8000.0)
}
}
但是我们也可以通过以下代码实现这一点并获得输出:
class A {
var name:String;
var salary:Float;
init(name:String,salary:Float) {
self.name = name;
self.salary = salary;
}
init(name:String) {
self.name = name;
self.salary = 8000.0;
}
init() {
self.name = "UnKnown name";
self.salary = 0.0;
}
}
let objectA = A(name: "murali")
print(objectA.name);
print(objectA.salary);
输出:
murali
8000.0
请说明我们将使用便利初始化器的哪些情况。
答案 0 :(得分:1)
在简单的情况下,例如使用convenience init
或手动设置属性没有太大区别。
在设置属性后,便捷初始化程序会派上用场,您必须执行一些复杂的逻辑并且不想复制代码。
此
class A {
var name:String;
var salary:Float;
init(name:String,salary:Float) {
self.name = name;
self.salary = salary;
//hundreds of line of very complicated logic in order to perform important stuff
}
convenience init(name:String) {
self.init(name:name , salary:8000.0)
}
}
比
更具可读性,更易于理解和管理未来的变更class B {
var name:String;
var salary:Float;
init(name:String,salary:Float) {
self.name = name;
self.salary = salary;
//hundreds of lines of very complicated logic in order to perform important stuff
}
init(name:String) {
self.name = name;
self.salary = 8000.0;
//the same, repeated, hundreds of lines as before of very complicated logic in order to perform the same important stuff
}
}