SwiftUI: What is and how to use @State property wrapper

Thaís Monteiro
Apple Developer Academy | UFPE
2 min readNov 15, 2022

In SwiftUI there are 17 types of property wrappers, each of which provide different functionality, but overall they all enable you to declare how each view interacts with mutable data.

In this article, we’re going to talk about the @State property wrapper

When you are dealing with properties that represent some form of state, it’s common to have some kind of associated logic that gets triggered when a value is changed.

When a @State value changes, any view with a reference to it invalidates its appearance and updates itself to display its new state.

This action of changing value can be made by an user that interacts with the application or an external event that publishes changes.

In the next section we’re going to create a simple interface that will change it’s theme according to users interactions.

How to use it

First, let’s build our view.

Now, we need a way to determine our background and foreground colors based on which button was pressed. So, we’re going to store this information inside a variable.

And then make the changes to the rest of our code.

If you run this code, you’ll notice that the value stored inside those variables has changed but our UI isn’t able to update.

That’s because we need a way to tell our view to watch those variables, becoming able to detect any changes and update itself when it’s needed. That’s when @State comes in.

It’s a good practice to mark your @State properties as private

Using this property wrapper inside of our view object allows it to respond to any changes made to @State.

In short, by doing this you are telling SwiftUI that a view is now dependent on some state. If the state changes, so should the User Interface.

SwiftUI will now manage the storage of this property, because we’ve declared it as state. Now our UI is updating according to user interaction.

Updating UI

Conclusion

Property wrappers opens up a lot of doors for code reuse and customizability.

If you need more details, you can check the source code on my Github repo and take a look at the official guidelines :)

--

--