Hi, I have probably a strange compiling error for the following code
import Foundation
class BB {
func process(val: @escaping () -> Void) {}
}
class AA {
let bb = BB()
func cc() -> Int? {
return nil
}
func fetch() {
bb.process { [weak self] in
guard let self = self else {
return
}
lazy var aa = self.cc
guard let a = aa() else {
return
}
}
}
}
Cannot reference invalid declaration 'self' but if I replace lazy var to just let it's gone.
import Foundation
class BB {
func proccess(val: @escaping () -> Void) {}
}
class AA {
let bb = BB()
func cc() -> Int? {
return nil
}
func fetch() {
bb.proccess { [weak self] in
guard let self = self else {
return
}
let aa = self.cc()
guard let a = aa else {
return
}
}
}
}
Can someone please explain is a bug or if this is correct behavior why?.
I'm using Xcode 13.3.1(Swift 5.6)
It's a quirk of lazy var that it's the only kind of instance property initialization that is allowed to reference self. It's not really a good quirk, but I think it hangs around because it is convenient sometimes (and would be source-breaking to remove).
This is interesting, and I don't know the answer. If you remove the code that uses the lazy var you get a different error:
error: class declaration cannot close over value 'self' defined in outer scope