Swift & Concurrency (50 Qs)•Part 1: Core Language, Memory & Value Types (1 - 10)
How does Swift Concurrency (`async/await`) work and how does it replace completion handlers?
senior LevelMost AskedCode ExampleAsync & Promises
In Simple Words: Before Swift 5.5, asynchronous code relied on nested completion handler closures, leading to "Callback Hell" and unhandled error states:
async/await: Writes asynchronous code that reads like synchronous procedural code:- When code hits
await, the execution thread is suspended, freeing the underlying OS thread to do other work. - When the asynchronous task completes, execution resumes on an available thread.
swift
// Modern async/await:
func loadProfile(userId: String) async throws -> Profile {
let url = URL(string: "https://api.com/users/\(userId)")!
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode(Profile.self, from: data)
}