The @State Property
Part of the Introduction to SwiftUI section of Coddy's Swift journey. Lesson 20 of 50.
A view's body is recomputed from its data. To have data that changes, mark a property with @State. When a state property changes, SwiftUI runs the body again and updates the screen:
struct ContentView: View {
@State private var count = 0
var body: some View {
VStack {
Text("Count: \(count)")
Button("Add one") {
count += 1
}
}
}
}Each tap runs count += 1, and the text shows the new number. You never update the text yourself: the text is described in terms of count, so it follows the value.
A plain var in a view cannot be changed from its body, because views are structs. @State stores the value outside the struct so it survives each redraw. Mark state private: it belongs to this view.
Challenge
EasyFinish the tap counter. The button's action is empty: make each tap add 1 to taps, so the text reads Taps: 1 after one tap and Taps: 2 after two.
Try it yourself
import SwiftUI
@main
struct CoddyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction to SwiftUI
Practice on your own: Swift playground