iOS Development SwiftUI Framework 2 — Questions and Answers
Question 1: What does `@ObservedObject` do in SwiftUI?
- Subscribes a view to updates from an external ObservableObject (Correct answer)
- Stores a reference type locally within a view
- Injects a dependency from the environment
- Persists state across view recreations
Correct answer: Subscribes a view to updates from an external ObservableObject
`@ObservedObject` watches an `ObservableObject` and re-renders the view whenever the object's `@Published` properties change.
Question 2: Which SwiftUI modifier adds padding around a view?
- .padding() (Correct answer)
- .frame()
- .offset()
- .spacing()
Correct answer: .padding()
The `.padding()` modifier adds insets around the view's content, with default or custom edge/size values.
Question 3: What is `@EnvironmentObject` used for in SwiftUI?
- Sharing an ObservableObject across many views without explicit passing (Correct answer)
- Reading system settings like color scheme
- Persisting data to iCloud
- Observing Core Data changes
Correct answer: Sharing an ObservableObject across many views without explicit passing
`@EnvironmentObject` allows views deep in the hierarchy to access a shared model object injected higher up, without passing it explicitly.
Question 4: Which SwiftUI view displays a scrollable list from a collection?
- List (Correct answer)
- ScrollView
- ForEach
- LazyVStack
Correct answer: List
`List` is SwiftUI's declarative component for displaying a scrollable, structured list of rows from a collection.
Question 5: What does the `.onAppear` modifier do in SwiftUI?
- Runs a closure when the view appears on screen (Correct answer)
- Animates the view's entry transition
- Sets the view's initial state
- Subscribes to a Combine publisher
Correct answer: Runs a closure when the view appears on screen
`.onAppear` attaches a side-effect closure that runs each time the view becomes visible on screen.
Question 6: How does SwiftUI handle navigation in iOS 16+?
- NavigationStack with navigationDestination modifier (Correct answer)
- UINavigationController wrapping
- Manual view swapping with @State
- NavigationView with EmptyView destinations
Correct answer: NavigationStack with navigationDestination modifier
In iOS 16+, `NavigationStack` combined with the `.navigationDestination(for:destination:)` modifier handles type-safe, programmatic navigation.
What does `@ObservedObject` do in SwiftUI?