How do I store state in modern SwiftUI apps?

Asked on 07/30/2024

1 search

To store state in modern SwiftUI apps, you can use several tools provided by SwiftUI, such as @State and @Binding. Here are the key points:

  1. State:

    • @State is used to create a new internal source of data for a view. SwiftUI manages the storage and provides it back for the view to read and write.
    • Example: If you have a view that allows you to rate your 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.
    • SwiftUI essentials (08:41)
  2. Binding:

    • @Binding creates a two-way reference to the state of some other view. This is useful when you need to pass state down to child views and allow them to modify it.
    • Example: If you have a parent view that holds the state and a child view that needs to modify this state, you can pass a binding to the child view.
  3. ObservableObject and @Published:

    • For more complex state management, you can use ObservableObject and @Published properties. An ObservableObject is a class that conforms to the ObservableObject protocol, and @Published properties within this class will automatically notify any observing views when they change.
    • Example: You can create an observable pet class that SwiftUI will track for changes. When a property in this class changes, SwiftUI will update any views that depend on this property.
    • SwiftUI essentials (09:43)

These tools help you manage state effectively in SwiftUI, ensuring that your UI stays in sync with your data.

Relevant Sessions