What is the difference between @ObservedObject, @StateObject, and @EnvironmentObject?

Why Interviewers Ask This

This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex Swift & iOS topics. It also reveals how well you can explain technical ideas to non-experts.

Answer

All three work with ObservableObject classes but differ in ownership and scope: @StateObject: the view owns the object — creates it and manages its lifetime. The object is created once and survives view re-renders: class ViewModel: ObservableObject { @Published var count = 0 } struct ParentView: View { @StateObject private var vm = ViewModel() // Owns -- created once var body: some View { Text("\(vm.count)") ChildView(vm: vm) } }. Use @StateObject when the view creates the object. @ObservedObject: the view does NOT own the object — it receives it from outside. The object is not preserved if the view is recreated: struct ChildView: View { @ObservedObject var vm: ViewModel // Doesn't own -- received from parent var body: some View { Button("Increment") { vm.count += 1 } } }. Use @ObservedObject when the object is passed in. @EnvironmentObject: injected into the view hierarchy — any descendant can access it without explicit passing: // At root: ContentView().environmentObject(UserStore()) // Any descendant: struct ProfileView: View { @EnvironmentObject var userStore: UserStore // Accessed from environment }. Crashes at runtime if the object isn't injected. ObservableObject + @Published: class CartStore: ObservableObject { @Published var items: [Item] = [] @Published var total: Double = 0 }. When @Published property changes, all observing views are automatically re-rendered. Summary: @StateObject = view creates it; @ObservedObject = view receives it; @EnvironmentObject = accessed from hierarchy.

Pro Tip

This topic has Swift & iOS-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.