ConcurrencyMidMCQ
What is the difference between `async/await` and GCD (Grand Central Dispatch)?
Test your knowledge:
Explanation & Code
Answer:
Both manage concurrent work, but async/await (introduced in Swift 5.5) is structured and compiler-checked, while GCD is unstructured and callback-based.
async/await | GCD | |
|---|---|---|
| Style | Structured | Unstructured |
| Readability | Linear code | Nested callbacks |
| Error handling | throws / try | Manual |
| Cancellation | Automatic (Tasks) | Manual |
| Thread safety | Enforced by actors | Manual |
Code Example:
// ❌ GCD — nested, harder to read and reason about
func loadUser(completion: @escaping (User?) -> Void) {
DispatchQueue.global().async {
let user = fetchFromNetwork()
DispatchQueue.main.async {
completion(user)
}
}
}
// ✅ async/await — reads like synchronous code
func loadUser() async throws -> User {
let user = try await fetchFromNetwork()
return user
}
Rate your understanding: