state in SWIFTUI

Asked on 06/16/2025

2 searches

In SwiftUI, state management is a fundamental concept that allows views to update dynamically in response to changes in data. SwiftUI provides several tools for managing state, including @State and @Binding.

  • State (@State): This is used to create an internal source of data for a view. When you mark a view property with @State, SwiftUI manages the storage and provides it back for the view to read and write. This allows the view to react to changes in the state and update its UI accordingly. For example, a view might use @State to keep track of a rating value that can be incremented or decremented by user interaction. SwiftUI automatically updates the UI when the state changes.

  • Binding (@Binding): This creates a two-way reference to the state of another view. It allows a child view to read and write to a state property owned by a parent view. This is useful for scenarios where multiple views need to stay in sync with a single source of truth. For instance, a container view might provide a binding to a child view so that both can update in sync when the state changes.

SwiftUI's declarative nature means that views are descriptions of what the UI should look like at any given state, and SwiftUI takes care of updating the UI when the state changes. This approach eliminates boilerplate code and reduces the likelihood of update bugs.

For more detailed information on state management in SwiftUI, you can refer to the session SwiftUI essentials (10:41).