Quick error using initialized properties in expressions before super.init

This is not critical, and there are workarounds, but it is bewildering.

See the minimum example below. I mean an initialized property, but before calling super.init (). Why does the instruction below have a compilation error? Is there anything special about using the property on the right side of the expression against the left hand?

I went through the Swift language guides and found nothing suitable. Is there a quick compiler here, or is there something about the self and init properties that I am missing? Or should all references to "myProperty" be in error before calling super.init?

(Note that it doesn't matter if the property is constant (with "let"), or if it is a different type, for example 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 */ }
    }
}
+4
source share
2 answers

This is a side effect ||declared as

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

So, the compiler is considering

true || myProperty

and

true || { self.myProperty }()

The reason is the "short circuit" of the operator behavior ||: if the first operand is true, then the second operand should not be evaluated at all.

(Lateral note: I assume that this is simplified at a later stage in the compilation / optimization of the process so that the final code does not actually create and does not cause closure.)

self .

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

, .

:

  • super.init, , init super.init
  • , self ,
0

All Articles