SwiftUI Basics: State

Jared Jarvis Williams
3 min readNov 12, 2020

In SwiftUI, views can keep state, meaning they can describe the content of the view in terms of the current state of some property inside of the view. Use the @State property wrapper before any property in a view struct to mark it as a state variable.

The code above creates a small view that keeps track of the number of times that the button is pressed. This is achieved by marking the count variable with the State property wrapper, this tells SwiftUI that anytime that the value of count changes that it should re-draw the view. When the button closure modifies the value of count, SwiftUI recomputes the value of the body property, and because the button uses the value of count for its label, the button will reflect the new value of count.

The @State property wrapper can be even more useful when used with bindings, bindings allow you to pass around references to your SwiftUI state variables so that they can be modified by child views, while still providing the functionality of triggering a re-draw when modified.

The above code creates a view with a button that, when pressed, displays an alert with the text “Hello <name>”, where <name> is the value of the variable name. In order to have our TextField modify our name state variable, we must pass it a Binding to the state variable. A Binding for any state variable is accessed by prefixing a state variable’s name with a $. By passing a binding to the TextField we in effect bind the current text inside of the text field to the variable name, and vice versa. This is intuitive, for when we press the button we see that the alert displays the message with the name from the text field.

Now let us see how the binding can be used in reverse

The above code has been modified so that the Button closure sets the name state property to “No name”, this demonstrates the two-way nature of bindings. When the name state property is modified in the Button closure, a re-draw of the view is triggered by SwiftUI, and because the TextField holds a reference to the Binding of the name state property, the TextField’s text will update to reflect the new value of name.

So to recap, Views can contain state that express the View’s content with respect to the value of the state. To mark a View struct property as a state variable prefix it with the @State property wrapper. Every state variable has a binding that can be accessed with $<someStateVar>, this binding can be used to bind the value of the state variable with some child view, and keeps the state variable in sync with the internal representation of another View.

--

--