Lifetime of object when using withCheckedContinuation and weak var

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()

If I am not mistaken lifetime of the local variable "delegate" (and thus the Delegate object it strongly holds) may end up as early as right after the last usage, which is "runner.delegate = delegate" line. A slightly modified version of your app that shows this potentiality:

func main() async {
    var delegate: Delegate? = Delegate()

    print("Start")
    await withCheckedContinuation { continuation in
        let runner = Runner {
            continuation.resume()
        }
        runner.delegate = delegate
        delegate = nil // oops
        runner.run()
    }
    print("End")
}

In other words there is no guarantee your code will work correctly (other than because of Hyrum's Law protection). You may find this recent pitch interesting, it may change the current state of affairs in this area.

1 Like