Swift lazy instantiating using self

后端 未结 1 1234
梦毁少年i
梦毁少年i 2020-11-27 07:39

I have something that really puzzles me, specifically the following code triggers a compiler error \"unresolved identifier self\", and I am not sure why this is happening, a

相关标签:
1条回答
  • 2020-11-27 08:26

    For some reason, a lazy property needs an explicit type annotation if its initial value refers to self. This is mentioned on the swift-evolution mailing list, however I cannot explain why that is necessary.

    With

    lazy var first: FirstClass = FirstClass(second: self)
    //            ^^^^^^^^^^^^
    

    your code compiles and runs as expected.

    Here is another example which demonstrates that the problem occurs also with structs, i.e. it is unrelated to subclassing:

    func foo(x: Int) -> Int { return x + 1 }
    
    struct MyClass {
        let x = 1
    
        lazy var y = foo(0)            // No compiler error
        lazy var z1 = foo(self.x)      // error: use of unresolved identifier 'self'
        lazy var z2: Int = foo(self.x) // No compiler error
    }
    

    The initial value of y does not depend on self and does not need a type annotation. The initial values of z1/z2 depend on self, and it compiles only with an explicit type annotation.

    Update: This has been fixed in Swift 4/Xcode 9 beta 3, lazy property initializers can now reference instance members without explicit self, and without explicit type annotation. (Thanks to @hamish for the update.)

    0 讨论(0)
提交回复
热议问题