Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to make the class notify views about changes.
iOS Swift
class UserSettings: [1] { @Published var score = 0 }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using View or State instead of ObservableObject.
Forgetting to conform to any protocol.
✗ Incorrect
The class must conform to ObservableObject to notify views when data changes.
2fill in blank
mediumComplete the code to mark a property that triggers view updates.
iOS Swift
class Settings: ObservableObject { [1] var isDarkMode = false }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using @State inside ObservableObject class.
Using @ObservedObject or @EnvironmentObject incorrectly.
✗ Incorrect
@Published marks properties that send change notifications to views.
3fill in blank
hardFix the error in the view to observe the object correctly.
iOS Swift
struct ContentView: View {
[1] var settings = Settings()
var body: some View {
Text(settings.isDarkMode ? "Dark" : "Light")
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using @ObservedObject when the view creates the object.
Using @Published in a view property.
✗ Incorrect
@StateObject creates and owns the ObservableObject in the view lifecycle.
4fill in blank
hardFill both blanks to observe an existing object passed from parent view.
iOS Swift
struct DetailView: View {
[1] var settings: Settings
var body: some View {
Toggle("Dark Mode", isOn: $settings.[2])
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using @StateObject for passed-in objects.
Binding to a property not marked @Published.
✗ Incorrect
Use @ObservedObject to observe an object passed in, and bind to its @Published property.
5fill in blank
hardFill all three blanks to create and observe an object in a parent view and pass it to a child view.
iOS Swift
struct ParentView: View {
[1] var settings = Settings()
var body: some View {
ChildView([2]: settings)
}
}
struct ChildView: View {
[3] var settings: Settings
var body: some View {
Text(settings.isDarkMode ? "Dark" : "Light")
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using @ObservedObject in parent view for object creation.
Not passing the object with the correct parameter name.
Using @Published in views.
✗ Incorrect
Parent uses @StateObject to create the object, passes it as 'settings', child uses @ObservedObject to observe it.