I’m wondering about lifetime of an object that is passed through withCheckedContinuation function to a weak variable. Is there any guarantee that the passed object won’t be deallocated until after withCheckedContinuation finishes?
In the following example I’m creating Delegate class and passing it to delegate property of Runner. Delegate should not be deallocated unit “End” is reached. Quick tests show that this is the case, but are there optimizations that would make this assumption invalid?
import Foundation
class Delegate {
init() {
print("Delegate.init")
}
deinit {
print("Delegate.deinit")
}
}
class Runner {
weak var delegate: Delegate?
private let completion: () -> Void
init(completion: @escaping () -> Void) {
self.completion = completion
}
func run() {
print("Running")
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
print("Completion")
self.completion()
}
}
}
func main() async {
let delegate = Delegate()
print("Start")
await withCheckedContinuation { continuation in
let runner = Runner {
continuation.resume()
}
runner.delegate = delegate
runner.run()
}
print("End")
}
await main()