Concurrency
Use async/await and actors to keep shared state safe.
What you will be able to do
- Use async functions for asynchronous work.
- Use Task to start concurrent work.
- Use actors for shared mutable state.
- Hop to @MainActor for UI updates.
In plain English
Swift concurrency uses async functions and tasks. await suspends without blocking the thread. Actors protect mutable state. UI work belongs on the main actor.
struct LessonService {
func load() async throws -> [Lesson] {
try await Task.sleep(nanoseconds: 100_000_000)
return []
}
}
@MainActor
final class LessonsViewModel: ObservableObject {
@Published var lessons: [Lesson] = []
func load() async throws { lessons = try await LessonService().load() }
}Your turn
EasyLoad on the main actor
Annotate a view model class with @MainActor.
SWIFT · starter
final class ViewModel {Check your understanding before moving on.
Knowledge checkQuestion 1
What does await do?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.