来自文档
安全检查一
指定的初始化式必须确保所有属性
类引入的初始化
超类初始值设定项。
我们为什么需要这样的安全检查?
为了回答这个问题,让我们在swift中经历初始化过程。
Two-Phase Initialization
Class initialization in Swift is a two-phase process. In the first
phase, each stored property is assigned an initial value by the class
that introduced it. Once the initial state for every stored property
has been determined, the second phase begins, and each class is given
the opportunity to customize its stored properties further before the
new instance is considered ready for use.
The use of a two-phase initialization process makes initialization
safe, while still giving complete flexibility to each class in a class
hierarchy. Two-phase initialization prevents property values from
being accessed before they are initialized, and prevents property
values from being set to a different value by another initializer
unexpectedly.
为了确保两步初始化过程按照上面定义的那样完成,有四个安全检查,其中一个是,
安全检查一
指定的初始化式必须确保所有属性
类引入的初始化
超类初始值设定项。
现在,两相初始化从来不讲顺序,但是这个安全检查,引入了super。Init是有序的,在初始化所有属性之后。
安全检查1可能看起来无关紧要,
两阶段初始化可以防止属性值在初始化之前被访问,而不需要进行此安全检查1。
就像这个样本
class Shape {
var name: String
var sides : Int
init(sides:Int, named: String) {
self.sides = sides
self.name = named
}
}
class Triangle: Shape {
var hypotenuse: Int
init(hypotenuse:Int) {
super.init(sides: 3, named: "Triangle")
self.hypotenuse = hypotenuse
}
}
三角形。Init在使用之前已经初始化了所有属性。所以安全检查1似乎无关紧要,
但可能还有另一种情况,有点复杂,
class Shape {
var name: String
var sides : Int
init(sides:Int, named: String) {
self.sides = sides
self.name = named
printShapeDescription()
}
func printShapeDescription() {
print("Shape Name :\(self.name)")
print("Sides :\(self.sides)")
}
}
class Triangle: Shape {
var hypotenuse: Int
init(hypotenuse:Int) {
self.hypotenuse = hypotenuse
super.init(sides: 3, named: "Triangle")
}
override func printShapeDescription() {
super.printShapeDescription()
print("Hypotenuse :\(self.hypotenuse)")
}
}
let triangle = Triangle(hypotenuse: 12)
输出:
Shape Name :Triangle
Sides :3
Hypotenuse :12
Here if we had called the super.init before setting the hypotenuse, the super.init call would then have called the printShapeDescription() and since that has been overridden it would first fallback to Triangle class implementation of printShapeDescription(). The printShapeDescription() of Triangle class access the hypotenuse a non optional property that still has not been initialised. And this is not allowed as Two-phase initialization prevents property values from being accessed before they are initialized
因此,确保两阶段初始化是按照定义完成的,需要有一个特定的顺序调用super。init,也就是在初始化self类引入的所有属性之后,因此我们需要一个安全检查1