How does SwiftUI's State management work?

Asked on 09/06/2024

1 search

SwiftUI's state management is a key feature that allows views to be state-driven, meaning that when your view's state changes over time, SwiftUI automatically updates the UI. This eliminates the need for boilerplate code and reduces update bugs.

In SwiftUI, state is managed using several tools, including @State and @Binding.

  • @State: This is used to create a new 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. For example, if you have a view that allows you to rate a pet's tricks, you can use @State to keep track of the current rating and change it over time. SwiftUI maintains the value of this state behind the scenes and updates the UI when the state changes.

  • @Binding: This creates a two-way reference to the state of another view. It allows a child view to read and write a value owned by a parent view. For instance, if you have a container view that combines a gauge and a rating view, you can use @Binding to ensure that both views are synchronized with the same source of truth.

SwiftUI also supports animations that build on top of these data-driven updates. When you wrap a state change with an animation, SwiftUI applies a default or custom transition to the view updates.

For more detailed information, you can refer to the SwiftUI essentials session from WWDC 2024.

How does SwiftUI's State management work? | Ask WWDC