← Back to Swift Course | Chapter 13: Concurrency | Lesson 1 of 6

async/await Basics

async/await lets your code pause while waiting for something slow, without freezing everything else, and then pick back up right where it left off.

Declaring an async Function

Adding async after a function's parameter list marks it as asynchronous, allowing it to use await internally and requiring callers to await it too.

Example: Declaring an async Function

markup
func fetchGreeting() async -> String {
    return "Hello from an async function"
}

let message = await fetchGreeting()
print(message)

Awaiting Multiple async Calls in Sequence

Multiple await expressions run one after another in the order written, each suspending until its result is ready before moving to the next line.

Example: Awaiting Multiple async Calls in Sequence

markup
func fetchNumber() async -> Int {
    return 21
}

let first = await fetchNumber()
let second = await fetchNumber()
print("Sum: \(first + second)")
Common Mistakes
  1. Calling an async function without the await keyword; every call to an async function must be awaited.
  2. Forgetting a function must be marked async in its own signature before it's allowed to await other async calls inside it.
  3. Assuming await blocks the entire program; it only suspends the current task, letting other work proceed.
Chapter Summary
  • A function marked async can suspend and later resume without blocking the thread.
  • Calling an async function requires the await keyword at the call site.
  • await marks a potential suspension point where the function may pause.
  • async/await replaces older completion-handler-based asynchronous code with linear, readable syntax.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.