Bird
0
0

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

medium📝 Predict Output Q5 of 15
iOS Swift - State Management in SwiftUI
What will happen if you remove the @State wrapper from this variable?
struct ContentView: View {
  private var count = 0
  var body: some View {
    VStack {
      Text("Count: \(count)")
      Button("Add") {
        count += 1
      }
    }
  }
}
AThe count variable will update and UI will refresh correctly.
BThe count variable will update but UI will not refresh.
CThe count variable will remain constant and not update.
DThe code will not compile due to missing @State.
Step-by-Step Solution
Solution:
  1. Step 1: Understand what happens without @State

    The code compiles because 'count' is declared as 'var', which allows mutation in the button closure.
  2. Step 2: Why UI doesn't update

    SwiftUI only re-renders the view body when @State or @Binding changes. Mutating a plain 'var' does not trigger a re-render.
  3. Final Answer:

    The count variable will update but UI will not refresh. -> Option B
  4. Quick Check:

    Without @State, mutations do not trigger UI updates [OK]
Quick Trick: Without @State, UI does not refresh despite var mutations [OK]
Common Mistakes:
  • Thinking UI updates without @State
  • Assuming code won't compile (it compiles but logic fails)
  • Confusing @State with @Binding

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes