Bird
0
0

What is wrong with this SwiftUI code?

medium📝 Debug Q14 of 15
iOS Swift - State Management in SwiftUI
What is wrong with this SwiftUI code?
struct ContentView: View {
  @State var text: String
  var body: some View {
    TextField("Enter text", text: $text)
  }
}
ATextField cannot bind to @State variables
B@State variables must have an initial value
CThe body property must return a Button, not TextField
D@State cannot be used inside a struct
Step-by-Step Solution
Solution:
  1. Step 1: Check @State variable declaration

    @State variables must be initialized with a value when declared.
  2. Step 2: Identify missing initial value

    Here, 'text' has no initial value, causing a compile error.
  3. Final Answer:

    @State variables must have an initial value -> Option B
  4. Quick Check:

    @State needs initial value = A [OK]
Quick Trick: Always give @State variables a starting value [OK]
Common Mistakes:
  • Forgetting to initialize @State variables
  • Thinking @State can't bind to TextField
  • Confusing struct rules with @State usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes