安全检查#4
初始化程序无法调用任何实例方法,读取任何实例属性的值,或者在初始化的第一阶段完成之后将self作为值引用。
class Fruit {
var name: String
init(fruitName: String) {
// in phase one
self.name = fruitName; // using self during the property assignment
// phase one is complete
}
}
let orange = Fruit(fruitName: "Orange");
那么,这如何得到特殊的使用自我,并知道自己所指的是什么?
答案 0 :(得分:0)
或直到第一阶段之后将自身称为值 初始化完成。
这是第一阶段就绪的情况,您希望如何在没有自我的情况下分配实例的属性?一个更有用的例子是当你重写init方法时。
你不能在super.init()
之前使用self答案 1 :(得分:0)
在两阶段初始化中,阶段1在到达链的顶部时结束,并且链中的最后一个类确保其所有存储的属性都具有值。
这意味着:
class Fruit {
var name: String
init(fruitName: String) {
self.someFunction() // compilation error, since not all stored properties have value yet, self is not allowed to refer as a value
self.name = fruitName; // self is refer here only for initializing property
// phase one completed
self.someFunction() // no problem here
}
func someFunction() {
print("phase one completed")
}
}