🍎 Swift & iOS Intermediate

What is Swift concurrency (async/await)?

Answer

Swift 5.5 introduced structured concurrency with async/await, providing a cleaner alternative to completion handlers and GCD for asynchronous code. async function: func fetchUsers() async throws -> [User] { let url = URL(string: "https://api.example.com/users")! let (data, response) = try await URLSession.shared.data(from: url) guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw NetworkError.badResponse } return try JSONDecoder().decode([User].self, from: data) }. await — suspension point: when the runtime hits await, the current thread is freed to do other work; execution resumes when the awaited value is ready. Calling async functions: // In async context: let users = try await fetchUsers() // In SwiftUI: .task { await viewModel.loadUsers() } // From sync context: Task { await loadData() }. Task: the unit of async work. Task { /* async work */ } Task.detached { /* unstructured */ } // Cancel: let task = Task { await longWork() } task.cancel(). async let — parallel execution: async let users = fetchUsers() async let products = fetchProducts() let (u, p) = try await (users, products) // Both run concurrently. TaskGroup — dynamic parallelism: let results = try await withThrowingTaskGroup(of: User.self) { group in for id in ids { group.addTask { try await fetchUser(id: id) } } var users: [User] = [] for try await user in group { users.append(user) } return users }. MainActor: ensures code runs on main thread: @MainActor class ViewModel: ObservableObject {} @MainActor func updateUI() {} await MainActor.run { self.tableView.reloadData() }.