State and Data Flow

Control and respond to the flow of data and changes within your app’s models.

Overview

States and bindings connect views to your app’s underlying data model. When you declare a state, SwiftUI stores it for you and manages the state’s connections to its view. When the state updates, the view invalidates its appearance and updates itself. You can also connect animations to the state to animate how the view portrays the change.

Create bindings from members of your state to connect to individual views. Bindings offer two-way connections, so that onscreen controls can mutate the state. Bindings also have transactions to pass values between views.

Topics

Essentials

Handling User Input

In the Landmarks app, a user can flag their favorite places, and filter the list to show just their favorites. To create this feature, you’ll start by adding a switch to the list so users can focus on just their favorites, and then you’ll add a star-shaped button that a user taps to flag a landmark as a favorite.

View State

struct State

A property wrapper type that can read and write a value managed by SwiftUI.

struct Binding

A property wrapper type that can read and write a value owned by a source of truth.

Object Data

struct ObservedObject

A property wrapper type that subscribes to an observable object and invalidates a view whenever the observable object changes.

protocol ObservableObject

A type of object with a publisher that emits before the object has changed.

Environment Data

struct Environment

A property wrapper type that reads a value from the view’s environment.

struct EnvironmentValues

A collection of environment values propagated through a view hierarchy.

struct EnvironmentObject

A property wrapper type for an observable object supplied by a parent or ancestor view.

View Preferences

protocol PreferenceKey

A named value produced by a view.

Persistent Storage

struct FetchRequest

A property wrapper type that makes fetch requests and retrieves the results from a Core Data store.

Change Management

struct Transaction

The context of the current state-processing update.

protocol DynamicProperty

An interface for a stored variable that updates an external property of a view.

See Also

Data and Events

Gestures

Define interactions from taps, clicks, and swipes to fine-grained gestures.