Bird
0
0

What will happen if you remove @State from this variable?

medium📝 Predict Output Q5 of 15
iOS Swift - State Management in SwiftUI
What will happen if you remove @State from this variable?
struct ToggleView: View {
  var isOn = false
  var body: some View {
    Button(isOn ? "On" : "Off") {
      isOn.toggle()
    }
  }
}
AThe button will be disabled
BThe button will toggle and update label correctly
CThe app will crash at runtime
DThe button label will never update when tapped
Step-by-Step Solution
Solution:
  1. Step 1: Identify the role of @State

    Without @State, the variable is a constant for the view and does not trigger UI updates.
  2. Step 2: Understand the effect on UI

    Changing isOn without @State does not cause the view to refresh, so the label stays the same.
  3. Final Answer:

    The button label will never update when tapped -> Option D
  4. Quick Check:

    Missing @State prevents UI update [OK]
Quick Trick: State is needed for UI to react to changes [OK]
Common Mistakes:
  • Assuming UI updates without @State
  • Expecting app crash without @State
  • Thinking button disables automatically

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes