SwiftUI and State management: @State and @Binding

Jan 31, 2023

In IT, state management refers to the process of monitoring and maintaining the current state of a system.

Unlike UIKit, which allows you to update the view and the data model independently of each other, SwiftUI is designed so that it is impossible to change a view by accident. Thus, every time the data changes, we know what the state of our application is.

A simple example:
You log in with a username on an application, which will be displayed on several screens.
You change the username, save your change and return to the home page.
The username displayed is the previous one!

SwiftUI allows us to solve this kind of problem with property wrappers

@State  and @Binding

Consider this code: 

SwiftUI cannot track changes to simple variables or structures. They do not have a mechanism to publish their change.

If we want to modify the name variable, we can use @State, this property will redraw the view to display the last modification of the variable.

With @State, SwiftUI creates a binding for this variable, accessible with $name (it is described in the documentation as the projected value). It is used in the TextField, to allow the user to manipulate the variable. The Text struct will use the name property, which is the most up to date value.

@Binding is also very simple to use. The best case is when a child view need to access data in a parent view :

In the case above, ChildView and ParentView use the number variable to share the same state.

Both @State and @Binding are adapted to manage the local state (in the same Struct or related Struct) of our UI. And since they are used locally, a good practice is to mark them as private, so they can't be modified from outside.