Bird
0
0

Why does this code cause a compile error?

medium📝 Debug Q7 of 15
iOS Swift - State Management in SwiftUI
Why does this code cause a compile error?
struct ContentView: View {
  @State private var number = 0
  func increment() {
    number += 1
  }
  var body: some View {
    Button("Add", action: increment)
  }
}
AFunctions cannot modify @State variables outside the body property.
Bincrement() must be marked as mutating to modify @State.
C@State variables cannot be modified inside functions.
DThe increment function is missing the @State wrapper.
Step-by-Step Solution
Solution:
  1. Step 1: Understand mutability rules in Swift structs

    Functions that modify properties in structs must be marked mutating.
  2. Step 2: Check increment() function declaration

    increment() is not marked mutating, so it cannot modify the @State variable.
  3. Final Answer:

    increment() must be marked as mutating to modify @State. -> Option B
  4. Quick Check:

    Mutating functions needed to change struct properties [OK]
Quick Trick: Mark functions mutating to change struct properties [OK]
Common Mistakes:
  • Assuming @State variables are class properties
  • Forgetting mutating keyword in struct methods
  • Thinking @State variables can't be changed in functions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes