0Pricing
Swift Academy · Lesson

async let, Task, cancellation

Run work in parallel with async let , create independent Task s, and handle cancellation cooperatively.

async let, Task, cancellation is a free Swift Academy lesson on CoddyKit — lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What we cover

You will:

  • Start sibling work with async let
  • Launch independent units via Task { }
  • Respond to cancellation using cooperative checks

async let basics

async let starts child tasks in parallel inside the same scope; you must await before leaving the scope.

func loadA() async -> Int { try? await Task.sleep(nanoseconds: 200_000_000); return 1 }
func loadB() async -> Int { try? await Task.sleep(nanoseconds: 200_000_000); return 2 }

Task {
    async let a = loadA()
    async let b = loadB()
    // Both start immediately; awaiting joins them
    let sum = await (a + b)
    print("sum =", sum) // 3
}

Independent Task

Use Task {} to launch an independent task and later await t.value to get its result.

// Create an independent task (not tied to current scope)
func fetchMessage() async -> String {
    try? await Task.sleep(nanoseconds: 150_000_000)
    return "hello"
}

let t = Task { await fetchMessage() }
Task {
    print("from Task:", await t.value)  // waits for the independent task's result
}

Cancellation basics

Cancellation is cooperative. Check with Task.checkCancellation() (throws) or read Task.isCancelled and return early.

// A long-running job that checks for cancellation
enum WorkError: Error { case cancelled }

func longJob() async throws -> Int {
    var total = 0
    for i in 1...10 {
        try Task.checkCancellation()        // throws CancellationError if cancelled
        try? await Task.sleep(nanoseconds: 50_000_000)
        total += i
    }
    return total
}

let job = Task { try await longJob() }
Task {
    // Cancel after a short delay
    try? await Task.sleep(nanoseconds: 120_000_000)
    job.cancel()
    do {
        _ = try await job.value
    } catch {
        print("job cancelled")              // expected
    }
}

Parent → children cancel

When the parent task is cancelled, child tasks observe it and should exit quickly after a check.

// Propagate cancellation from parent to children using async let
func part(_ id: Int) async throws -> String {
    try Task.checkCancellation()
    try? await Task.sleep(nanoseconds: 80_000_000)
    return "P\(id)"
}

Task {
    do {
        async let p1 = part(1)
        async let p2 = part(2)
        // Cancel the whole operation before awaiting
        Task.currentTask?.cancel()   // cancel self -> children see cancellation
        let out = try await [p1, p2].joined(separator: ",")
        print(out)
    } catch {
        print("parent cancelled; children stopped")
    }
}

Guidelines

Tips:

  • Use async let for siblings; always await them in the same scope.
  • Cancel with task.cancel(), and inside work call Task.checkCancellation().
  • Prefer small async functions: easy to cancel and test.

Cooperative cancellation behavior

Quick check: How should long-running async code react to cancellation?

Recap

Recap: Start siblings with async let, launch independent work in Task {}, and implement cooperative cancellation by checking and exiting promptly.

Frequently asked questions

Is the “async let, Task, cancellation” lesson free?

Yes — the full text of “async let, Task, cancellation” is free to read here on the web, and the Swift Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “async let, Task, cancellation”?

Run work in parallel with async let , create independent Task s, and handle cancellation cooperatively. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “async let, Task, cancellation” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Structured concurrency, async functions
  2. async let, Task, cancellation
  3. try await and error propagation
← Back to Swift Academy