SwiftQuiz
#3

Task Cancellation and async let

  • concurrency
Swift 6.3.2 Report an issue

Verified quizzes have their expected answer checked by compiling and running the code with the listed Swift toolchain during the site build.

let task = Task {
    async let a = { () async in
        defer { print("after waiting a") }
        await withCheckedContinuation { cont in
            Task {
                try await Task.sleep(for: .seconds(2))
                cont.resume(returning: ())
            }
        }
    }()

    async let b = { () async throws in
        defer { print("after waiting b") }
        try await Task.sleep(for: .seconds(5))
    }()

    print("end of task")
}

await task.result
Hint

Three things to untangle: when does the body of an async let actually run, what happens when the task finishes, and does a Task { … } spawned inside a regular function inherit cancellation from its caller?

Your answer

What does this program do?