What is Swift concurrency (async/await)?
Why Interviewers Ask This
This question targets practical, hands-on experience with Swift & iOS. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.
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() }.
Common Mistake
A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.