Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare an observed object in a SwiftUI view.
iOS Swift
struct ContentView: View {
@ObservedObject var viewModel = [1]()
var body: some View {
Text(viewModel.title)
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a struct instead of a class for the observed object.
Forgetting to mark the class with ObservableObject protocol.
✗ Incorrect
You use @ObservedObject to watch an instance of a class that conforms to ObservableObject, like MyViewModel.
2fill in blank
mediumComplete the code to update the view when the observed object changes.
iOS Swift
class MyViewModel: ObservableObject { @Published var count = 0 } struct ContentView: View { @ObservedObject var viewModel = MyViewModel() var body: some View { Button(action: { viewModel.count [1] 1 }) { Text("Count: \(viewModel.count)") } } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using = instead of +=, which replaces the value instead of adding.
Using the wrong operator like -= which subtracts.
✗ Incorrect
To increase the count by 1, use the += operator.
3fill in blank
hardFix the error in the observed object declaration to properly update the view.
iOS Swift
class Counter: ObservableObject { var value = 0 } struct ContentView: View { @ObservedObject var counter = [1]() var body: some View { Text("Value: \(counter.value)") } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the protocol name ObservableObject instead of the class name.
Using @StateObject instead of @ObservedObject in this context.
✗ Incorrect
The observed object must be an instance of the class Counter.
4fill in blank
hardFill both blanks to declare a published property and update it correctly.
iOS Swift
class TimerModel: ObservableObject { @[1] var seconds = 0 func tick() { seconds [2] 1 } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using @State instead of @Published inside ObservableObject.
Using = instead of += which replaces the value.
✗ Incorrect
Use @Published to mark properties that trigger view updates. Use += to add 1 to seconds.
5fill in blank
hardFill all three blanks to create an observed object, update a published property, and display it.
iOS Swift
class ScoreModel: ObservableObject { @[1] var score = 0 func increase() { score [2] 10 } } struct ScoreView: View { @ObservedObject var model = ScoreModel() var body: some View { VStack { Text("Score: \(model.[3])") Button("Add 10") { model.increase() } } } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong property name in the Text view.
Forgetting to mark the property with @Published.
✗ Incorrect
Use @Published for the property, += to add 10, and 'score' to display the property.