@State — local view data
struct CounterView: View {
@State private var count = 0
var body: some View {
Button("Count: \(count)") { count += 1 }
}
}
@Binding — share editable state with a child
struct NameField: View {
@Binding var name: String
var body: some View { TextField("Name", text: $name) }
}
// parent passes $name (a binding)
ObservableObject for shared data
class Cart: ObservableObject {
@Published var items: [String] = []
}
struct CartView: View {
@StateObject private var cart = Cart() // owns the object
var body: some View { Text("\(cart.items.count) items") }
}
@EnvironmentObject (app-wide)
// inject once at the top
ContentView().environmentObject(Cart())
// read anywhere below
@EnvironmentObject var cart: Cart
Quick guide: simple value here → @State; passed to a child → @Binding; shared class → @StateObject/@ObservedObject; whole app → @EnvironmentObject.