The @State SwiftUI Property Wrapper

Mutable state in SwiftUI

Steven Curtis


Photo by Kit Suman on Unsplash

Although I’ve labeled this article as beginner, I’ve noticed that my previous article about property wrappers just didn’t make it seem so. So I think it really asks for a new article about the @State property wrapper.

Difficulty: Beginner | Easy | Normal | Challenging



Property Wrapper: A property wrapper adds a layer of separation between code that manages how a property is stored and the code that defines a property

@State: a property wrapper used to create a single source of truth for data in your app which mutates over time (and updating a view appropriately).

The @State property wrapper

In Swift, a struct is used to store variables of different data types and views are simple structs.

This leads us to a problem. This problem is that a view struct does not have a mutating function where you can change it’s properties. This means that @State is a solution to this issue, as it can be used to manage mutable state in SwiftUI in the view struct.

By using the @State keyword we communicate to Swift that SwiftUI can manage this property in shared storage. Put simply, that means that SwiftUI will automatically re-render a view that is dependent on that property as necessary. When the state changes, SwiftUI knows to redraw or "recompose" the view.

All this is better shown with an example (as usual).

Before I go into detail I’ll show the easiest example. A isButtonPressed property is marked with the @State keyword and is correctly marked with private as the access control (since @State properties are generally accessible by a single view).

@State private var isButtonPressed = false

Note that @State properties are usually initialized with a default value for the initial render of a view. Subsequent to this the value is managed by SwiftUI and persists across view updates, so @State properties should not be accessed in a view’s initializer.