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 annotationAdd a
text property of type String inside ViewModelWrite an async function
updateText() inside ViewModel that changes textCall
updateText() from outside the class using awaitPrint 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