struct ContentView: View {
@State private var count = 0
var body: some View {
VStack {
Text("Count: \(count)")
Button("Tap me") {
count += 1
}
}
}
}The @State property wrapper marks the variable as mutable state for the view. When the button increments count, SwiftUI re-renders the view and updates the Text to show the new value.
@State variables must be declared as properties of the View struct, outside the body property. Declaring inside body or closures is invalid.
struct ContentView: View {
@State var name: String
var body: some View {
Text("Hello, \(name)!")
}
}@State variables must have an initial value because SwiftUI manages their storage. Declaring without initialization causes a compile error.
struct ContentView: View {
var count = 0
var body: some View {
VStack {
Text("Count: \(count)")
Button("Tap") {
count += 1
}
}
}
}Without @State, changing 'count' does not notify SwiftUI to update the UI. The variable is just a normal property and changes are ignored for UI refresh.
@State marks data that belongs to a view and can change over time. When the data changes, SwiftUI automatically refreshes the view to reflect the new state.