ios – Swift 2阶段初始化安全检查4


Language Guide – Initialization中所规定的,Swift 2两阶段类初始化涉及4次安全检查.第四个内容如下

An initializer cannot call any instance methods, read the values of
any instance properties, or refer to self as a value until after the
first phase of initialization is complete
.

第一阶段的完成描述为

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 …

现在,请考虑以下示例:

class A {
    var a: Int
    init() {
        a = 2
    }
}

class B: A {
    var b: Int
    override init() {
        self.b = 8 // (thanks @vadian)
        //First Case: OK
        var b = self.b
        b += 1

        //Second Case: error
        var ab = self.a
        ab += 1

        super.init()
    }
}

第二种情况产生预期的编译时错误

Use of self in property access a before super.init which makes sense
because a is not initialized.

但是,第一种情况是有效的.根据安全检查4,它应该无效,因为我们在第一阶段完成之前使用self.

这里的结论是什么?安全检查4,如语言指南中所述,不完全正确吗?

最佳答案 首先,你必须为self.b分配8,因为编译器将b视为局部变量 – 后面声明一行 – 抛出此错误

use of local variable ‘b’ before its declaration

规则是

>首先初始化(子)类的所有实例变量
>调用super来初始化基类的其他实例变量
>使用自我

所以B级应该是

class B: A {
  var b: Int

  override init() {

    self.b = 8
    //First Case
    var b = self.b

    b += 1

    super.init()

    //Second Case
    var ab = self.a
    ab += 1
  }

}

我想编译器会在幕后做这样的事情

let tmp = 8
self.b = tmp
//First Case
var b = tmp
点赞