The @State property wrapper lets your app remember and update values that can change over time. It helps your app update the screen automatically when data changes.
0
0
@State property wrapper in iOS Swift
Introduction
When you want to keep track of a button tap count and show it on the screen.
When you need to update a text field as the user types.
When you want to toggle a switch and change the UI based on its state.
When you want to show or hide parts of the screen based on user actions.
Syntax
iOS Swift
@State private var variableName: Type = initialValue
Use
@State only inside SwiftUI views to hold simple, local data.Mark the variable as
private to keep it safe inside the view.Examples
A boolean state to track if a switch is on or off.
iOS Swift
@State private var isOn: Bool = false
An integer state to count button taps.
iOS Swift
@State private var count: Int = 0A string state to hold user input text.
iOS Swift
@State private var username: String = ""Sample App
This app shows a button and a text label. Each time you tap the button, the number increases and the text updates automatically. This happens because count is marked with @State, so SwiftUI knows to refresh the screen when it changes.
iOS Swift
import SwiftUI struct ContentView: View { @State private var count: Int = 0 var body: some View { VStack(spacing: 20) { Text("Button tapped: \(count) times") .font(.title) Button("Tap me") { count += 1 } .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(8) } .padding() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
OutputSuccess
Important Notes
Only use @State for simple, local data inside one view.
For sharing data between views, use other tools like @ObservedObject or @EnvironmentObject.
Changing a @State variable automatically refreshes the view to show the new data.
Summary
@State keeps track of changing data inside a SwiftUI view.
It automatically updates the screen when the data changes.
Use it for simple, local variables like counters, toggles, or text inputs.