Sobes.tech
Junior — Middle

What are the differences between using the @State annotation for a variable and the @ObservedObject annotation in SwiftUI?

sobes.tech AI

Answer from AI

@State is used for local state within a single View. A variable with @State is stored and managed by the View itself, and when it changes, the View is re-rendered. This is suitable for simple values that do not need to be passed between different Views.

@ObservedObject is used to track objects that conform to the ObservableObject protocol and may contain multiple @Published properties. Changes in these properties trigger updates in all Views observing this object. This is convenient for sharing state between multiple Views.

Example:

class UserSettings: ObservableObject {
    @Published var score = 0
}

struct ContentView: View {
    @State private var localCounter = 0
    @ObservedObject var settings = UserSettings()

    var body: some View {
        VStack {
            Text("Local: \(localCounter)")
            Button("Increment Local") { localCounter += 1 }

            Text("Score: \(settings.score)")
            Button("Increment Score") { settings.score += 1 }
        }
    }
}

Here, localCounter is the local state of the View, and settings is an object that can be used in other Views as well.