Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a property that automatically notifies views when it changes.
iOS Swift
class ViewModel: ObservableObject { [1] var count = 0 }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using @State instead of @Published inside ObservableObject.
Forgetting to mark the class as ObservableObject.
✗ Incorrect
The @Published attribute marks a property so that changes to it notify any observing views.
2fill in blank
mediumComplete the code to make the ViewModel class notify views about changes.
iOS Swift
class ViewModel: [1] { @Published var name = "" }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using View or StateObject instead of ObservableObject for the class.
Not conforming to any protocol.
✗ Incorrect
ObservableObject is the protocol that allows a class to notify views about changes in @Published properties.
3fill in blank
hardFix the error in the code by completing the property declaration to notify views.
iOS Swift
class Settings: ObservableObject { [1] var isOn = false func toggle() { isOn.toggle() } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using @State or @Binding inside ObservableObject classes.
Not marking the property at all.
✗ Incorrect
Only properties marked with @Published notify views when they change inside ObservableObject classes.
4fill in blank
hardFill both blanks to declare a published property and initialize it.
iOS Swift
class UserSettings: ObservableObject { [1] var username: String = [2] }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting @Published.
Initializing with empty quotes instead of a meaningful default.
✗ Incorrect
The property must be marked @Published and initialized with a string value like "Guest".
5fill in blank
hardFill all three blanks to create a published integer property with a default value and a method to increment it.
iOS Swift
class Counter: ObservableObject { [1] var count: Int = [2] func increment() { count [3] 1 } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using -= instead of += to increment.
Not marking count as @Published.
✗ Incorrect
The count property is marked @Published, starts at 0, and increments by 1 using +=.