Free beta. ExpertKin is new and still changing, and paying isn't open yet. Send feedback

ExpertKin
Build Apps: Make Your App Do Something

Free preview lesson

Making the Screen Remember Things with @State

What @State means in plain language

Why this matters: a screen in SwiftUI is rebuilt again and again as things change. If a value is just a normal variable, it gets reset every time the screen is rebuilt. You need a place where the screen can keep a value safely while the app is running.

That place is called @State. The @ symbol is a marker that tells SwiftUI, Apple's toolkit for building app screens, to watch this value. Think of @State as a small labeled box that your screen owns. The box holds a value, such as a number or some text.

Here is how it works:

  1. Declare a variable with @State, for example @State private var count = 0.
  2. Show it in your view, for example Text("Count: (count)").
  3. Change the value later, and SwiftUI automatically redraws the screen so the new value appears.

The word private means only this screen can touch the box. That is the normal choice for @State. Notice that you never call a refresh function yourself. Changing the box is enough.

It is important to know that @State values live only while the screen is on the device's memory. They are not saved to disk, so they reset when the app closes. Saving data comes later in the course.

What to do now: open your screen file, add @State private var counter = 0 above your body, and show the counter in a Text view. Run the simulator and confirm the number appears.