Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a state variable in a SwiftUI view.
Swift
struct ContentView: View {
[1] var count = 0
var body: some View {
Text("Count: \(count)")
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using @Published inside a View struct instead of @State.
Forgetting the @ symbol before the property wrapper.
✗ Incorrect
Use @State to declare a local state variable inside a SwiftUI view.
2fill in blank
mediumComplete the code to declare a published property in an ObservableObject class.
Swift
class Counter: ObservableObject { [1] var value = 0 }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using @State inside a class instead of @Published.
Not conforming the class to ObservableObject.
✗ Incorrect
Use @Published to mark properties that notify views when they change in ObservableObject classes.
3fill in blank
hardFix the error in the code by choosing the correct property wrapper for a view model property.
Swift
struct ContentView: View {
@StateObject var model = Counter()
var body: some View {
Text("Value: \(model.[1])")
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to use @Published or @State when accessing the property.
Using nested property names incorrectly.
✗ Incorrect
Access the published property directly by its name without property wrappers in the view body.
4fill in blank
hardFill both blanks to declare a published property and update it inside a class.
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 '=' instead of '+=' to increment.
Using @State inside a class instead of @Published.
✗ Incorrect
Use @Published to mark the property and '+=' to increment it.
5fill in blank
hardFill all three blanks to declare a state variable, update it, and display it in a SwiftUI view.
Swift
struct ClickCounter: View {
[1] var count = 0
var body: some View {
VStack {
Text("Count: \(count)")
Button("Increment") {
count [2] [3] 1
}
}
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using @Published instead of @State in a view.
Using '=' instead of '+=' to update the variable.
✗ Incorrect
Declare count with @State, increment it with '+=' and add 1 with '+'.