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.
Why modern concurrency matters in 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.
func loadImage() async -> UIImage { // pretend to load image return UIImage() } Task { let image = await loadImage() print("Image loaded") }
Task.sleep to pause without freezing the app.Task {
print("Start")
try? await Task.sleep(nanoseconds: 2_000_000_000) // wait 2 seconds
print("End")
}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.
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))
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.
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.
Practice
async and await in Swift?Solution
Step 1: Understand what concurrency means
Concurrency means doing multiple tasks at once, which helps apps stay responsive.Step 2: Connect concurrency with
These keywords let Swift run tasks without waiting and freezing the app.asyncandawaitFinal Answer:
It allows your app to do many tasks at the same time without freezing. -> Option BQuick Check:
Modern concurrency = smooth multitasking [OK]
- Thinking concurrency slows the app down
- Confusing concurrency with more memory use
- Believing async/await removes functions
Solution
Step 1: Recall Swift async function syntax
In Swift,asynccomes after the function parentheses.Step 2: Check each option's syntax
Only func fetchData() async -> String placesasynccorrectly after the parentheses.Final Answer:
func fetchData() async -> String -> Option AQuick Check:
async keyword after () = correct syntax [OK]
- Placing async before func
- Inserting async inside parameter list
- Putting async before return type
func fetchNumber() async -> Int {
return 10
}
Task {
let number = await fetchNumber()
print(number)
}Solution
Step 1: Understand async function behavior
The functionfetchNumber()returns 10 asynchronously.Step 2: Check how Task and await work
The Task runs the async code, andawaitwaits for the result before printing.Final Answer:
10 -> Option DQuick Check:
await fetchNumber() returns 10 [OK]
- Forgetting to use await
- Expecting print before result is ready
- Thinking async functions run instantly
func loadData() async -> String {
return "Data"
}
func printData() {
let result = await loadData()
print(result)
}Solution
Step 1: Check where await is used
The functionprintData()usesawaitinside its body.Step 2: Confirm async requirement for await
Any function usingawaitmust be markedasync.Final Answer:
Missing async keyword in printData function declaration -> Option CQuick Check:
await requires async function [OK]
- Not marking function async when using await
- Thinking await can be used in normal functions
- Confusing async with return type
Solution
Step 1: Understand sequential vs concurrent calls
Calling await one after another waits for the first to finish before starting the second.Step 2: Use async let for concurrency
Usingasync letstarts both tasks simultaneously, improving speed.Final Answer:
Use async let to start both fetchUser() and fetchPosts() at the same time, then await both results. -> Option AQuick Check:
async let = concurrent tasks [OK]
- Awaiting tasks one by one causing delay
- Mixing synchronous and asynchronous calls incorrectly
- Using old concurrency methods instead of async/await
Ready to prove it?
Pass the test and this pattern moves unknown
