Swift error using initialized properties in expressions before super.init

前端 未结 2 979
忘了有多久
忘了有多久 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 ||(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
    }
    

提交回复
热议问题