[25] async / await Flashcards

(42 cards)

1
Q

What does async/await solve? async/await

A

Linear, structured async code — no callback pyramids.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Mark an async function async/await

A
func fetchUser() async throws -> User { ... }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Call an async function async/await

A
let user = try await fetchUser()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is a Task? async/await

A

A Task in Swift Concurrency allows you to call async methods inside a synchronous context. Take the following two methods:

func someSynchronousMethod() {
    Task {
        await someAsynchronousMethod()
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Why would I want to keep a reference of a task?

A

A task runs regardless of whether you track it. However, without a reference, you can’t wait for its results or cancel its execution.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Task cancellation basics async/await

A

Cooperative: check

Task.isCancelled // This can be useful if you don’t want the task to fail but return a default value instead.

or

try Task.checkCancellation(). // Throw and error if the task was already cancelled

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

check if task was cancelled async / await

A
let task = Task {
    print("This is first")
    
    let sum = (1...100000).reduce(0, +)
    try Task.checkCancellation()
    print("This is second")
}

print("This is last")
task.cancel()

Output:
~~~

This is first
This is last
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What happens if a user cancels a task that have child tasks?

A

If a parent task is canceled, all of its child tasks are also automatically notified about the cancellation. Child tasks implicitly link to their parent, meaning their cancellation state links as well.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is a detached Task? async/await

A

A detached task in Swift Concurrency is an independent unit of async work that doesn’t inherit priority, actor context, or task-local values from its parent; you use it for fire-and-forget work that must run outside the caller’s context.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Create a detached task async/await

A
let handle = Task.detached { await compute() }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the risks of using detached tasks.

A

They won’t inherit the parent task’s priority and the task-local storage, and they won’t cancel if the parent task gets cancelled.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Summary on Detached Tasks

A

Detached tasks should be your last resort. Most of the time, you won’t need them, and you’re able to solve the same using regular child tasks, async let, or task groups.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is async let? async/await

A

Declares a child task within the current scope that begins running immediately and can be awaited later, allowing structured concurrency.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

async let example async/await

A
async let a = fetchA()
async let b = fetchB()
let (ra, rb) = await (a, b)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Why TaskGroup? async/await

A

Dynamically spawn many children and collect results.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Throwing TaskGroup sample async/await

A
let r = try await withThrowingTaskGroup(of:Int.self){ g in
  for n in 1...10 {
	g.addTask { try await work(n) } 
 }
  var out:[Int]=[]
for try await x in g {
	out.append(x) 
	}
  return out
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is an actor? async/await

A

Reference type with isolated mutable state; prevents data races.

18
Q

What is @MainActor? async/await

A

Enforces main-thread execution for UI-affecting code.

19
Q

@MainActor example async/await

A
@MainActor func updateUI(){
/* UIKit/SwiftUI */ 
}
20
Q

Define an actor async/await

A
actor Counter { var value=0; func inc(){ value+=1 } }
21
Q

Call actor from outside async/await

A
let c = Counter(); await c.inc()
22
Q

What is nonisolated? async/await

A

Access without hopping into actor (constants/pure funcs).

23
Q

nonisolated sample async/await

A
actor A { nonisolated let id = UUID() }
24
Q

What is Sendable? async/await

A

Type safe to pass across concurrency domains.

25
Make type Sendable `async/await`
``` struct Safe: Sendable { let x:Int } ```
26
Sleep in a task `async/await`
``` swift try await Task.sleep(nanoseconds: 500_000_000) ```
27
AsyncSequence basics `async/await`
Produces values over time; consume with for await.
28
Consume an AsyncSequence `async/await`
```swift for await line in socket.lines { print(line) } ```
29
Bridge callbacks → async `async/await`
```swift func load() async throws -> Data { try await withCheckedThrowingContinuation { cont in api.load { cont.resume(with: $0) } } } ```
30
Actors vs queues `async/await`
Prefer actors over manual locking/queues for Swift 5.9+.
31
What is a global actor? `async/await`
Shared executor to serialize access across types.
32
Define a global actor `async/await`
```swift @globalActor struct ModelActor: GlobalActor { static let shared = ModelActor() } ```
33
Task priority `async/await`
Set on creation; maps to QoS.
34
Priority example `async/await`
```swift Task(priority: .userInitiated) { await work() } ```
35
Structured vs unstructured `async/await`
Structured tied to scope; unstructured Task{} is independent.
36
Class isolation vs actor `async/await`
Classes aren’t isolated; guard with actors/locks/queues.
37
Actor reentrancy `async/await`
Actors are reentrant; invariants must tolerate interleaving across awaits.
38
@MainActor & SwiftUI `async/await`
Views run on main; mark model changes affecting UI as @MainActor.
39
URLSession with await `async/await`
```swift let (data, _) = try await URLSession.shared.data(from: url) ```
40
Migrate from GCD to async/await `async/await`
Prefer async/await; wrap legacy APIs with continuations; keep GCD for sources/interop.
41
Common pitfall `async/await`
Forgetting await or calling async from sync—wrap in Task{} or make caller async.
42
Testing async code `async/await`
Use async XCTest with await and expectations/for-await.