Complete the code to declare a state variable in SwiftUI.
@State private var count: [1] = 0
The @State property wrapper requires a type declaration. Here, count is an integer, so Int is correct.
Complete the code to update the state variable when the button is pressed.
Button(action: {
count [1] 1
}) {
Text("Increment")
}To increase the count by 1, use the += operator.
Fix the error in the code to display the count value in the Text view.
Text("Count: \( [1] )")
Use the variable name count directly inside string interpolation without parentheses.
Fill both blanks to create a reactive view that updates when the state changes.
struct ContentView: View {
@State private var count: [1] = 0
var body: some View {
VStack {
Text("Count: \(count)")
Button(action: {
count [2] 1
}) {
Text("Add")
}
}
}
}The state variable count is an integer (Int), and to update it reactively, use += to add 1.
Fill all three blanks to create a SwiftUI view that shows a toggle and text reflecting its state.
struct ToggleView: View {
@State private var isOn: [1] = false
var body: some View {
VStack {
Toggle(isOn: $[2]) {
Text("Switch")
}
Text(isOn ? [3] : "Off")
}
}
}The toggle state is a boolean (Bool). The binding uses $isOn. The text shows "On" when true.