Posts

Showing posts from August, 2025

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

SwiftUI - Tutorial 1 - 🔥 Understanding Data Flow in SwiftUI: @StateObject, @ObservedObject, and @EnvironmentObject

🔥 Understanding Data Flow in SwiftUI: @StateObject , @ObservedObject , and @EnvironmentObject When you first start learning SwiftUI, all these property wrappers can feel confusing: @State @Binding @StateObject @ObservedObject @EnvironmentObject Don’t worry 🙌 This guide will explain the three most important ones for managing data models in SwiftUI: @StateObject @ObservedObject @EnvironmentObject And we’ll also touch on the other related wrappers ( @State , @Binding , @AppStorage , etc.). 🟢 1. @StateObject – When the View Creates the Object Use @StateObject when your view is responsible for creating and owning the object . SwiftUI will keep this object alive as long as the view exists. ✅ Example: class CounterViewModel : ObservableObject { @Published var count = 0 func increment () { count += 1 } } struct CounterView : View { @StateObject private var vm = CounterViewModel () // View owns it var body: some Vie...