SwiftUI - Tutorial 2 - 🧵 Understanding @MainActor in SwiftUI — A Beginner’s Guide
🧵 Understanding @MainActor in SwiftUI — A Beginner’s Guide When you start building iOS apps with SwiftUI , sooner or later you’ll run into this warning: ⚠️ “Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates.” Sounds scary? Don’t worry 🙂 This is exactly where @MainActor comes to the rescue. 🔹 What is @MainActor ? In Swift, an actor is like a traffic controller that makes sure only one thing accesses a resource at a time. The @MainActor is a special actor provided by Swift that guarantees the code it marks will always run on the main thread . And that’s important because in iOS development: UI updates must always happen on the main thread. 🔹 Why do we need @MainActor in SwiftUI? SwiftUI automatically refreshes the UI when your @Published properties change. But if those changes happen on a background thread (for example, after fetching data from ...