Lifetime of object when using withCheckedContinuation and weak var

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