Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a state variable named count initialized to 0.
iOS Swift
@[1] var count = 0
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using @Binding instead of @State
Forgetting the '@' symbol
Using @ObservedObject for simple state
✗ Incorrect
The @State property wrapper is used to declare a state variable that SwiftUI monitors for changes.
2fill in blank
mediumComplete the code to update the state variable count by incrementing it by 1 inside the button action.
iOS Swift
Button(action: {
count [1] 1
}) {
Text("Increment")
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-=' which subtracts instead of adds
Using '*' or '/' operators which multiply or divide
✗ Incorrect
The '+=' operator adds the value on the right to the variable on the left, updating the state.
3fill in blank
hardFix the error in the code by completing the declaration of the state variable inside a SwiftUI View struct.
iOS Swift
struct CounterView: 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 'var' without @State causes the UI not to update
Using 'let' which is immutable
Using @Published which is for ObservableObject classes
✗ Incorrect
Inside a View struct, state variables must be marked with @State to allow SwiftUI to track changes.
4fill in blank
hardFill in the blank to create a button that toggles a Boolean state variable named isOn.
iOS Swift
@State var isOn = false
Button(action: {
isOn [1] !isOn
}) {
Text(isOn ? "On" : "Off")
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' which is a comparison, not assignment
Using '!=' which is a comparison operator
Using '+=' which is for numeric addition
✗ Incorrect
The '=' operator assigns the negated value of isOn back to isOn, toggling the Boolean state.
5fill in blank
hardFill the two blanks to declare a state variable count, increment it in a button, and display it in a Text view.
iOS Swift
struct ContentView: View {
@[1] var count = 0
var body: some View {
VStack {
Button(action: {
count [2] 1
}) {
Text("Increment")
}
Text("Count: \(count)")
}
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using @StateObject or @ObservedObject for simple Int state
Using '=' instead of '+=' to increment
Forgetting to mark count with @State
✗ Incorrect
Use @State to declare the variable, '+=' to increment it, and display count in Text. @StateObject and @ObservedObject are for classes, not simple state.