Modern concurrency helps your app do many things at once without freezing or slowing down. It makes programs faster and smoother, just like a busy kitchen where many cooks work together without bumping into each other.
0
0
Why modern concurrency matters in Swift
Introduction
When your app needs to download pictures while still letting the user tap buttons.
When you want to load data from the internet and show it without waiting for everything to finish.
When you have tasks that take time, like reading files or processing information, and you don't want the app to stop working.
When you want to run multiple tasks at the same time to save waiting time.
When you want your app to feel quick and responsive even if it's doing a lot behind the scenes.
Syntax
Swift
func fetchData() async throws -> Data { // Your code to fetch data } Task { do { let data = try await fetchData() print("Data received") } catch { print("Error fetching data") } }
async marks a function that can pause and wait for work without blocking the app.
await tells the program to wait for a task to finish before moving on.
Examples
This example shows a simple async function that loads an image and waits for it inside a Task.
Swift
func loadImage() async -> UIImage { // pretend to load image return UIImage() } Task { let image = await loadImage() print("Image loaded") }
This example uses
Task.sleep to pause without freezing the app.Swift
Task {
print("Start")
try? await Task.sleep(nanoseconds: 2_000_000_000) // wait 2 seconds
print("End")
}Sample Program
This program shows how to fetch a number asynchronously with a delay. It prints messages before and after waiting, so you see the app stays responsive.
Swift
import Foundation import UIKit func fetchNumber() async -> Int { // Simulate a delay try? await Task.sleep(nanoseconds: 1_000_000_000) // 1 second return 42 } Task { print("Fetching number...") let number = await fetchNumber() print("Number received: \(number)") } // Keep the program running to see output RunLoop.main.run(until: Date().addingTimeInterval(2))
OutputSuccess
Important Notes
Modern concurrency uses async and await to make code easier to read and write.
Using concurrency correctly prevents your app from freezing or feeling slow.
Always test your async code to make sure it handles errors and delays well.
Summary
Modern concurrency lets your app do many things at once smoothly.
Use async and await to write clear, non-blocking code.
This helps apps stay fast and responsive, improving user experience.