SwiftUI SwiftUI State and Data Flow 2 — Questions and Answers
Question 1: How do you pass an `@EnvironmentObject` to a child view?
- Pass it as an init parameter
- Use `.environmentObject()` modifier on the parent view (Correct answer)
- Declare it with @State in the parent
- Use @Binding in the child
Correct answer: Use `.environmentObject()` modifier on the parent view
You inject the object into the environment using `.environmentObject()`, making it available to all descendant views.
Question 2: What happens to a `@State` variable when a SwiftUI view is destroyed and recreated?
- It retains its value
- It resets to its initial value (Correct answer)
- It is saved to disk automatically
- It triggers an animation
Correct answer: It resets to its initial value
SwiftUI resets `@State` to its initial value each time the view's identity changes and it is recreated.
Question 3: Which property wrapper reads a value from SwiftUI's environment without requiring it to be an ObservableObject?
- @EnvironmentObject
- @Environment (Correct answer)
- @AppStorage
- @SceneStorage
Correct answer: @Environment
`@Environment` reads values from the environment using a key path, such as `\.colorScheme` or `\.locale`.
Question 4: What is the purpose of `@AppStorage` in SwiftUI?
- Stores data in iCloud
- Provides a binding to a UserDefaults key (Correct answer)
- Manages in-memory app-wide state
- Persists state across scene sessions
Correct answer: Provides a binding to a UserDefaults key
`@AppStorage` wraps UserDefaults, automatically updating the view when the stored value changes.
Question 5: How do you create a `Binding` value manually in SwiftUI?
- Binding(get: { value }, set: { value = $0 })
- Binding.constant(value)
- State.binding(value)
- Both A and B are valid for different purposes (Correct answer)
Correct answer: Both A and B are valid for different purposes
You can create a custom Binding with get/set closures or use `Binding.constant()` for a read-only binding in previews.
Question 6: What does the `$` prefix do when used with a `@State` property?
- Reads the wrapped value
- Projects a Binding to the state (Correct answer)
- Forces an immediate view update
- Accesses the publisher
Correct answer: Projects a Binding to the state
Prefixing a `@State` property with `$` accesses its projected value, which is a `Binding` that child views can use to read and write the state.
How do you pass an `@EnvironmentObject` to a child view?