Swift·Swift from optionals to SwiftUI

Concurrency

Use async/await and actors to keep shared state safe.

Beginner 14 min read Lesson 7 of 300 Challenge included
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.

Concurrency.swiftSwift
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

Load on the main actor

Easy

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 in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: SwiftUI basics
Lesson 7 of 300 · 0% of course