what should I use to manage the state of my swiftui view?

Generated on 10/17/2024

1 search

To manage the state of your SwiftUI view, you can use several tools provided by SwiftUI. The primary ones are @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. This is useful for managing the state that is local to a view.

  • @Binding: This creates a two-way reference to the state of some other view. It allows a child view to read and write a value owned by a parent view.

For example, in the session "SwiftUI essentials," it is explained how @State is used to keep track of the current rating in a view, and SwiftUI automatically updates the UI when the state changes. This is demonstrated with a view that allows rating a pet's tricks, where the state is used to manage the current rating and update it over time.

For more details, you can refer to the SwiftUI essentials (10:41) session.