🍎 Swift & iOS Intermediate

What is the difference between synchronous and asynchronous operations in iOS?

Answer

Synchronous operations block the calling thread until completion. Asynchronous operations return immediately and deliver results later via callbacks, delegates, Combine, or async/await. Why async matters on iOS: the main thread handles all UI updates, touch events, and animations at 60fps. Any work longer than ~16ms on the main thread causes visual stutter ("jank"). Network calls, file I/O, heavy computation MUST be on background threads. Patterns for async work: (1) Completion handlers (old style): func loadImage(url: URL, completion: @escaping (UIImage?) -> Void) { DispatchQueue.global().async { let data = try? Data(contentsOf: url) let image = data.flatMap { UIImage(data: $0) } DispatchQueue.main.async { completion(image) // Back to main for UI } } }; (2) async/await (modern): func loadImage(url: URL) async throws -> UIImage { let (data, _) = try await URLSession.shared.data(from: url) guard let image = UIImage(data: data) else { throw ImageError.invalid } return image } // Usage: Task { let image = try await loadImage(url: url) await MainActor.run { imageView.image = image } }; (3) Combine: URLSession.shared.dataTaskPublisher(for: url) .map { UIImage(data: $0.data) } .receive(on: DispatchQueue.main) .sink(receiveCompletion: { _ in }, receiveValue: { image in imageView.image = image }).store(in: &cancellables). Deadlock prevention: never dispatch sync to the same queue you're on. Never block the main thread with sync calls. Use async APIs for network, disk, and heavy computation.