swift初始化总结

Swift在初始化过程中遇到的一些问题,这里结合理论总结一下。

错误1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Parent {
var a: Int

init() {
a = 10
}
}

class Child: Parent {
var b: Int
var c: Int

override init() {
super.init()
b = 1
c = 2
}
}

这种情况下会提示“Property self.b not initialize at super.init call”,这是由于这种写法违反了Swift的4条安全检查的第一条:

1
2
3
Safety check 1

A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.

所以Child的init正确的写法是这样的:

1
2
3
4
5
override init() {
b = 1
c = 2
super.init() // 到目前为止完成了Two-Phase Initialize的第一个步骤
}