@State Property Wrapper Explained

Sergey Chsherbak
2 min readDec 2, 2021

SwiftUI uses many property wrappers, but in the present article let’s cover one particular — @State and answer the next questions:

  • What is the @State property wrapper?
  • When it is used?

Every view in SwiftUI is a struct. We also know that structs are value types, which means that they are immutable, and we cannot modify their values inside of them. Consider the following example:

On line number 9 you will get the error message that says: “Cannot use mutating member on immutable value: ‘self’ is immutable”.

SwiftUI comes with @State exactly for this purpose. With it, we can modify values inside structs.

So, when we mark a property inside a struct with @State we tell Swift that this property can be changed in our program and thus can have different states.
Under the hood, SwiftUI manages it and stores this property somewhere, where it can be changed over time.
To simplify it all, every time you write @State before the property of a struct, you say that this value will change as your program runs.

But aside from being able to modify this property inside of a struct, SwiftUI does one more incredible thing. It monitors this value for changes. And when the value changes SwiftUI knows that it needs to update its view according to this new value.

Thanks for reading!

if you enjoyed this article, be sure to give it a clap so others will find it more easily.

--

--