Property wrappers like @State and @Published help you keep track of data that can change. They automatically update your app's screen when the data changes.
Built-in property wrappers (@State, @Published) in Swift
import SwiftUI struct ContentView: View { @State private var count: Int = 0 var body: some View { Button("Tap count: \(count)") { count += 1 } } } class Model: ObservableObject { @Published var name: String = "" }
@State is used inside SwiftUI views to hold simple, local state.
@Published is used inside classes that conform to ObservableObject to notify views when data changes.
@State holding a number inside a view.struct CounterView: View { @State private var count: Int = 0 var body: some View { Text("Count is \(count)") } }
@Published inside a class to notify changes.class UserSettings: ObservableObject { @Published var username: String = "Guest" }
@State with a toggle switch to change a boolean value.struct EmptyStateView: View { @State private var isOn: Bool = false var body: some View { Toggle("Switch", isOn: $isOn) } }
@Published property in a model class.class SingleValueModel: ObservableObject { @Published var value: Int = 0 }
This program shows how @State keeps track of a local number inside the view, and @Published updates the user name in a shared data model. Pressing buttons changes the values and updates the screen automatically.
import SwiftUI class UserData: ObservableObject { @Published var name: String = "Alice" } struct ContentView: View { @State private var localCount: Int = 0 @ObservedObject var userData = UserData() var body: some View { VStack(spacing: 20) { Text("Local count: \(localCount)") Button("Increment Local Count") { localCount += 1 } Text("User name: \(userData.name)") Button("Change User Name") { userData.name = "Bob" } } .padding() } } @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } }
Time complexity: Reading and writing @State and @Published properties is very fast, constant time.
Space complexity: Minimal extra memory is used to store the wrapped values and observers.
Common mistake: Trying to use @State outside of a SwiftUI view or forgetting to mark a class as ObservableObject when using @Published.
Use @State for simple, local state inside views. Use @Published inside shared data models to notify multiple views.
@State keeps simple, local data inside a SwiftUI view and updates the UI when it changes.
@Published marks properties inside a class to notify views when data changes.
Both help your app stay in sync with data changes without extra code.