0
0
Swiftprogramming~30 mins

MainActor for UI work in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using MainActor for UI Work in Swift
📖 Scenario: You are building a simple Swift app that updates a label on the screen. UI updates must happen on the main thread to keep the app smooth and avoid crashes.
🎯 Goal: Learn how to use @MainActor to ensure UI updates happen safely on the main thread.
📋 What You'll Learn
Create a class called ViewModel with a @MainActor annotation
Add a text property of type String inside ViewModel
Write an async function updateText() inside ViewModel that changes text
Call updateText() from outside the class using await
Print the updated text property
💡 Why This Matters
🌍 Real World
UI updates in iOS apps must happen on the main thread to avoid glitches and crashes. Using <code>@MainActor</code> helps keep UI code safe and organized.
💼 Career
Understanding <code>@MainActor</code> is important for Swift developers working on iOS apps, especially when dealing with concurrency and UI updates.
Progress0 / 4 steps
1
Create ViewModel class with @MainActor and text property
Create a class called ViewModel and annotate it with @MainActor. Inside it, create a variable text of type String initialized to "Hello".
Swift
Need a hint?

Use @MainActor before the class declaration to mark it for UI work.

2
Add async function updateText() to change text
Inside the ViewModel class, add an async function called updateText() that sets text to "Updated Text".
Swift
Need a hint?

Define updateText() as an async function that changes the text property.

3
Create ViewModel instance and call updateText() with await
Outside the ViewModel class, create an instance called viewModel. Then write an async context (like Task) and call await viewModel.updateText() inside it.
Swift
Need a hint?

Use Task { await viewModel.updateText() } to call the async function.

4
Print the updated text property
Inside the same Task block, after calling await viewModel.updateText(), add a print(viewModel.text) statement to show the updated text.
Swift
Need a hint?

Use print(viewModel.text) to display the updated text.