Jan 21, 2025 iOS

What is the role of @State, @Binding, @ObservedObject, and @EnvironmentObject in SwiftUI? Provide examples.

@state

@State in SwiftUI is a property wrapper used to manage simple, local state within a single view. It enables the view to update its UI whenever the value of the @State property changes.

Key Characteristics of @State

  1. Local State: @State is designed for state that belongs exclusively to a single view. It cannot be shared with other views.
  2. Automatic UI Updates: Changes to a @State property automatically trigger the view to re-render, ensuring the UI stays in sync.
  3. Immutable to the View: Although marked as mutable, @State properties are read-only from the perspective of the view body. The changes must be made using the underlying binding.
struct TextInputView: View {
    @State private var name: String = ""

    var body: some View {
        VStack {
            TextField("Enter your name", text: $name)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .padding()

            Text("Hello, \(name)!")
                .font(.title)
                .padding()
        }
        .padding()
    }
}

Limitations of @State

  1. Local to View: Cannot share state with other views. Use @Binding, @ObservedObject, or @EnvironmentObject for shared state.
  2. Small, Simple State: Use @State for lightweight state only. For more complex or shared state, consider ObservableObject.

Index