0
0
iOS Swiftmobile~20 mins

@State property wrapper in iOS Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
SwiftUI State Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
ui_behavior
intermediate
2:00remaining
What happens when you tap the button?
Consider this SwiftUI code snippet using @State. What will the Text display after tapping the button once?
iOS Swift
struct ContentView: View {
  @State private var count = 0
  var body: some View {
    VStack {
      Text("Count: \(count)")
      Button("Tap me") {
        count += 1
      }
    }
  }
}
AThe Text updates to show "Count: 1"
BThe Text stays at "Count: 0" because @State does not update UI
CThe app crashes because count is immutable
DThe Text shows "Count: 0" but the button becomes disabled
Attempts:
2 left
💡 Hint
Remember that @State allows the view to update when the variable changes.
lifecycle
intermediate
1:30remaining
Where should @State variables be declared?
Which of these is the correct place to declare an @State variable in a SwiftUI view?
AInside the body property of the View
BAs a private property inside the View struct, outside the body
CIn the AppDelegate class
DInside the Button action closure
Attempts:
2 left
💡 Hint
Think about where properties live in a struct.
📝 Syntax
advanced
2:00remaining
What error does this code produce?
What error will this SwiftUI code cause?
iOS Swift
struct ContentView: View {
  @State var name: String
  var body: some View {
    Text("Hello, \(name)!")
  }
}
ANo error, code runs fine
BCannot use @State with String type
CMissing body property error
DProperty 'name' must have an initial value or be optional
Attempts:
2 left
💡 Hint
Check how @State variables must be initialized.
🔧 Debug
advanced
2:00remaining
Why does the UI not update?
Given this code, why does the Text not update when the button is tapped?
iOS Swift
struct ContentView: View {
  var count = 0
  var body: some View {
    VStack {
      Text("Count: \(count)")
      Button("Tap") {
        count += 1
      }
    }
  }
}
ABecause the Button action is empty and does not change count
BBecause the Text view is outside the VStack
CBecause 'count' is not marked with @State, so changes don't trigger UI updates
DBecause 'count' is a constant and cannot be changed
Attempts:
2 left
💡 Hint
Think about what triggers SwiftUI to refresh the view.
🧠 Conceptual
expert
2:30remaining
What is the role of @State in SwiftUI?
Which statement best describes the purpose of the @State property wrapper in SwiftUI?
A@State stores mutable data owned by a view and triggers UI updates when changed
B@State is used to declare constants that never change
C@State shares data between multiple views without copying
D@State manages network requests asynchronously
Attempts:
2 left
💡 Hint
Consider how SwiftUI knows when to redraw a view.