@State Property Wrapper Explained

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.

--

--

--

22 y.o. iOS Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Firefuel Basics

Understanding Swift Closures

How To Create a Framework With Carthage Support

iOS Interview Questions and Answers for Senior Developers Part 3 — Persistence & Databases

Debounce a method

Migrating to Vapor 4

Using Breadth-First Search for LeetCode Problems

Recreating the Sandwiches SwiftUI WWDC Code

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sergey Chsherbak

Sergey Chsherbak

22 y.o. iOS Developer

More from Medium

UIView File Structuring

Basic Operators in Swift

iOS testing — 4 crossroads technique — Part 2