SwiftUI SwiftUI State and Data Flow 1 — Questions and Answers
Question 1: What property wrapper is used to declare local mutable state in a SwiftUI view?
- @Binding
- @ObservedObject
- @State (Correct answer)
- @EnvironmentObject
Correct answer: @State
`@State` declares a source of truth owned by the view for simple value types.
Question 2: What does `@Binding` do in SwiftUI?
- Creates a new state variable
- Creates a two-way connection to a state owned by another view (Correct answer)
- Observes changes in an ObservableObject
- Reads environment values
Correct answer: Creates a two-way connection to a state owned by another view
`@Binding` provides a reference to state stored elsewhere, allowing a child view to read and write it.
Question 3: Which property wrapper connects a view to an external ObservableObject instance?
- @State
- @Binding
- @ObservedObject (Correct answer)
- @Published
Correct answer: @ObservedObject
`@ObservedObject` tells the view to re-render when the observed object's published properties change.
Question 4: What protocol must a class conform to in order to be used with `@ObservedObject` or `@StateObject`?
- Identifiable
- Codable
- ObservableObject (Correct answer)
- Equatable
Correct answer: ObservableObject
A class must conform to `ObservableObject` and mark properties with `@Published` to trigger view updates.
Question 5: When should you use `@StateObject` instead of `@ObservedObject`?
- When the object is passed from a parent view
- When the view owns and creates the object (Correct answer)
- When sharing data across the app
- When the object is a value type
Correct answer: When the view owns and creates the object
`@StateObject` should be used when the view is responsible for creating and owning the object's lifetime.
Question 6: What does marking a property with `@Published` inside an ObservableObject do?
- Makes the property read-only
- Automatically notifies subscribers when the property changes (Correct answer)
- Persists the property to UserDefaults
- Marks the property as thread-safe
Correct answer: Automatically notifies subscribers when the property changes
`@Published` uses Combine to emit a change event whenever the property's value is set, triggering view re-renders.
What property wrapper is used to declare local mutable state in a SwiftUI view?