SwiftUIMidMCQ
What is the difference between `@State`, `@Binding`, `@ObservedObject`, and `@StateObject`?
Test your knowledge:
Explanation & Code
Answer: These are SwiftUI's property wrappers for state management — each has a distinct ownership and lifecycle role.
| Wrapper | Owns data? | Source |
|---|---|---|
@State | ✅ Yes | Local to the view |
@Binding | ❌ No | Passed in from parent |
@StateObject | ✅ Yes | Owns the ObservableObject |
@ObservedObject | ❌ No | Injected from outside |
@EnvironmentObject | ❌ No | Injected via environment |
Code Example:
// Parent creates and owns the object
struct ParentView: View {
@StateObject private var viewModel = CounterViewModel()
var body: some View {
ChildView(count: $viewModel.count) // passes binding
}
}
// Child receives a binding — does not own the data
struct ChildView: View {
@Binding var count: Int
var body: some View {
Button("Increment") { count += 1 }
}
}
Key Rule:
- Use
@StateObjectwhen the view creates the object - Use
@ObservedObjectwhen the object is created elsewhere and passed in
Rate your understanding: