简体   繁体   English

Swift 1.2:在super.init调用之前使用的'self'

[英]Swift 1.2: 'self' used before super.init call

I have this code: 我有以下代码:

class SomeViewController : UIViewController {

 let deferred : ()->()

 required init(coder aDecoder : NSCoder) {
    deferred = {
        self.doSomething()
    }

    super.init(coder: aDecoder)
 }

 func doSomething() {
    // Does things....
 }

}

In Swift 1.2 this fails to compile with the error: 在Swift 1.2中,无法编译并显示以下错误:

'self' used before super.init call 在super.init调用之前使用“自我”

In pre-1.2 days, we can address this in a number of ways such as implicitly unwrapped conditionals. 在1.2天内,我们可以通过多种方式解决此问题,例如隐式展开条件。 That approach won't work any longer. 这种方法将不再起作用。

I've seen other answers reference 2-stage initialization or the lazy decorator, but both sacrifice immutability of the property. 我看到了其他参考两阶段初始化或惰性装饰器的答案,但两者都牺牲了属性的不变性。 Surely this must be solvable in Swift 1.2, but I'm out of ideas. 当然,这在Swift 1.2中必须可以解决,但是我没有想法。

Here's an interim workaround: 这是一个临时解决方法:

private(set) var deferred : ()->() = { }

required init(coder aDecoder : NSCoder) {
    super.init(coder: aDecoder)
    self.deferred = {
        self.doSomething()
    }

}

My thinking is, okay, we did "sacrifice immutability of the property", but from a public perspective the property remains immutable because the setter is private. 我的想法是,我们做到了“牺牲财产的不变性”,但是从公众的角度来看,财产是不变的,因为二传手是私人的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM