Generic Structure

State

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

Declaration

@frozen @propertyWrapper struct State<Value>

Overview

SwiftUI manages the storage of any property you declare as a state. When the state value changes, the view invalidates its appearance and recomputes the body. Use the state as the single source of truth for a given view.

A State instance isn’t the value itself; it’s a means of reading and writing the value. To access a state’s underlying value, use its variable name, which returns the wrappedValue property value.

You should only access a state property from inside the view’s body, or from methods called by it. For this reason, declare your state properties as private, to prevent clients of your view from accessing it. It is safe to mutate state properties from any thread.

To pass a state property to another view in the view hierarchy, use the variable name with the $ prefix operator. This retrieves a binding of the state property from its projectedValue property. For example, in the following code example PlayerView passes its state property isPlaying to PlayButton using $isPlaying:

struct PlayerView: View {
    var episode: Episode
    @State private var isPlaying: Bool = false
    
    var body: some View {
        VStack {
            Text(episode.title)
            Text(episode.showTitle)
            PlayButton(isPlaying: $isPlaying)
        }
    }
}

Topics

Creating a State

init()

Creates a state without an initial value.

init(wrappedValue: Value)

Creates the state with an initial wrapped value.

init(initialValue: Value)

Creates the state with an initial value.

Getting the Value

var wrappedValue: Value

The underlying value referenced by the state variable.

var projectedValue: Binding<Value>

A binding to the state value.

Updating the Value

func update()

Updates the underlying value of the state.

Relationships

Conforms To

See Also

View State

struct Binding

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