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, as lazy means that at the time the property will be used, the class is already instantiated. Am I missing something?
Many thanks in advance.
Here is the code
class FirstClass {
unowned var second: SecondClass
init(second:SecondClass) {
self.second = second
print("First reporting for duty")
}
func aMethod() {
print("First's method reporting for duty")
}
}
class SecondClass {
lazy var first = FirstClass(second: self)
func aMethod() {
first.aMethod()
}
}
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
your code compiles and runs as expected.
Here is another example which demonstrates that the problem occurs also with
struct
s, i.e. it is unrelated to subclassing:The initial value of
y
does not depend onself
and does not need a type annotation. The initial values ofz1/z2
depend onself
, 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.)