Swift – What does the SwiftUI `@State` keyword do

swiftswift5.1swiftui

The SwiftUI tutorial uses the @State keyword to indicate mutable UI state:

@State var showFavoritesOnly = false

It offers this summary:

State is a value, or a set of values, that can change over time, and that affects a view’s behavior, content, or layout. You use a property with the @State attribute to add state to a view.

  • What does the keyword mean, exactly?
  • How does mutating a @State variable cause the view to be recomputed?
  • How are other variables immutable within the body getter?

Best Answer

The @State keyword is a @propertyWrapper, a feature just recently introduced in Swift 5.1. As explained in the corresponding proposal, it's sort of a value wrapper avoiding boilerplate code.


Sidenote: @propertyWrapper has previously been called @propertyDelegate, but that has changed since. See this post for more information.


The official @State documentation has the following to say:

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 mutating the value. To access a state’s underlying value, use its value property.

So when you initialize a property that's marked @State, you're not actually creating your own variable, but rather prompting SwiftUI to create "something" in the background that stores what you set and monitors it from now on! Your @State var just acts as a delegate to access this wrapper.

Every time your @State variable is written, SwiftUI will know as it is monitoring it. It will also know whether the @State variable was read from the View's body. Using this information, it will be able to recompute any View having referenced a @State variable in its body after a change to this variable.

Related Topic