Swift error using initialized properties in expressions before super.init

前端 未结 2 980
忘了有多久
忘了有多久 2021-01-13 21:46

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

See the minimal example below. I\'m referring to an initialized property, but before callin

相关标签:
2条回答
  • 2021-01-13 22:19

    This is a side-effect of || being declared as

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

    So the compiler treats

    true || myProperty
    

    as

    true || { self.myProperty }()
    

    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.)

    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
    }
    
    0 讨论(0)
  • 2021-01-13 22:23

    I think it is intended behavior and part of the two phase initialization.

    This is a result of the following rules:

    • All properties must be initialized before super.init is called, that is at the same line as the declaration or in init before super.init
    • An initializer may not 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
    0 讨论(0)
提交回复
热议问题