在super.init之前的表达式中使用初始化属性的Swift错误 [英] Swift error using initialized properties in expressions before super.init

查看:69
本文介绍了在super.init之前的表达式中使用初始化属性的Swift错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这并不重要,有解决方法,但令人困惑.

This isn't critical, and there are workarounds, but it is perplexing.

请参见下面的最小示例.我指的是初始化属性,但是在调用super.init()之前.为什么以下指示的语句有编译错误?在表达式的右手相对于左手使用属性有什么特别之处吗?

See the minimal example below. I'm referring to an initialized property, but before calling super.init(). Why does the indicated statement below have a compile error? Is there something special about using the property in the right hand of an expression versus the left hand?

我浏览了Swift语言指南,找不到任何相关内容.是快速编译器搞砸了,还是我缺少的有关属性,自身和初始化的东西?还是在调用super.init之前 all 对"myProperty"的引用是错误的?

I looked through the Swift language guides and couldn't find anything relevant. Is the swift compiler screwing up here, or is there something about properties, self, and init that I'm missing? Or should all references to "myProperty" be in error before calling super.init?

(请注意,属性是一个常量(带有'let')还是属性是另一个类型(如Int),都一样.)

(Note it doesn't matter if the property is a constant (with 'let') or if the property is another type, like an Int - the same thing happens.)

class MyClass : NSObject {
    var myProperty: Bool

    override init() {
        myProperty = true

        if myProperty { /* this is ok */ }
        if myProperty || true { /* this is ok */ }
        if true || myProperty  { /* this is NOT ok! ('self used before super.init') - WHY? */ }

        super.init()

        if true || myProperty  { /* now this is ok */ }
    }
}

推荐答案

这是||被声明为

func ||<T : BooleanType>(lhs: T, rhs: @autoclosure () -> Bool) -> Bool

所以编译器会处理

true || myProperty

true || { self.myProperty }()

原因是||运算符的短路" 行为:如果第一个 操作数为true,则根本不能对第二个操作数求值.

The reason is the "short-circuiting" behaviour of the || operator: If the first operand is true, then the second operand must not be evaluated at all.

(旁注:我认为这是在后面的阶段中简化的 编译/优化过程 因此最终代码实际上不会创建并调用闭包.)

(Side note: I assume that this is simplified at a later stage in the compiling/optimizing process so that the final code does not actually create and call a closure.)

在闭包内部访问self会导致错误消息.你会 收到相同的错误

Accessing self inside the closure causes the error message. You would get the same error for

override init() {
    myProperty = true
    let a = { self }() // ERROR: self used before super.init
    super.init()
    let b = { self }() // OK after super.init
}

这篇关于在super.init之前的表达式中使用初始化属性的Swift错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆