Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a shared data model using @EnvironmentObject in SwiftUI.
iOS Swift
struct ContentView: View {
@EnvironmentObject var model: [1]
var body: some View {
Text(model.title)
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using @StateObject or @ObservedObject instead of @EnvironmentObject
Using a wrong type name that does not match the shared model
✗ Incorrect
Use the exact class name of the shared data model with @EnvironmentObject to access shared state.
2fill in blank
mediumComplete the code to inject the shared model into the environment in the app's root view.
iOS Swift
MyApp()
.environmentObject([1]()) Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a view type instead of the model
Using property wrapper names instead of the model class
✗ Incorrect
You create an instance of the shared data model class and inject it with .environmentObject().
3fill in blank
hardFix the error in accessing the shared model property in a child view.
iOS Swift
struct DetailView: View {
var model: [1]
var body: some View {
Text(model.title)
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the @EnvironmentObject wrapper
Using @StateObject or @ObservedObject in child views
✗ Incorrect
Child views must declare the shared model with @EnvironmentObject to access the injected shared state.
4fill in blank
hardFill both blanks to update the shared model's property and notify views.
iOS Swift
class SharedDataModel: ObservableObject { @Published var title = "Hello" func updateTitle(to newTitle: String) { self.title [1] newTitle } } struct ContentView: View { @EnvironmentObject var model: SharedDataModel var body: some View { Button(action: { model.title [2] "Welcome" }) { Text("Change Title") } } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using += or other operators that do not replace the value
Forgetting to assign the new value
✗ Incorrect
Use = to assign a new value to the published property so views update.
5fill in blank
hardFill all three blanks to create a SwiftUI view that reads and updates shared state correctly.
iOS Swift
struct ProfileView: View {
@EnvironmentObject var model: [1]
var body: some View {
VStack {
Text(model.[2])
Button("Update") {
model.[3] = "Updated"
}
}
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using method names instead of property names
Using wrong property names that do not exist
✗ Incorrect
Use the shared model class name, access the published property 'title', and assign a new value to it.