Challenge - 5 Problems
State Mastery in SwiftUI
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediateWhat happens when @State changes in SwiftUI?
Consider a SwiftUI view with a @State variable. What is the immediate effect on the UI when this state variable changes?
iOS Swift
struct ContentView: View {
@State private var count = 0
var body: some View {
VStack {
Text("Count: \(count)")
Button("Increment") {
count += 1
}
}
}
}Attempts:
2 left
💡 Hint
Think about how SwiftUI knows when to redraw parts of the screen.
✗ Incorrect
In SwiftUI, @State variables are special. When they change, SwiftUI automatically redraws the parts of the UI that depend on them, so the UI stays in sync with the data.
🧠 Conceptual
intermediateWhy use @State for UI updates in SwiftUI?
Why is it important to use @State for variables that affect the UI in SwiftUI?
Attempts:
2 left
💡 Hint
Think about how SwiftUI knows what to update when data changes.
✗ Incorrect
@State marks a variable as reactive. SwiftUI watches it and refreshes the UI automatically when it changes, keeping UI and data in sync.
❓ lifecycle
advancedWhat happens if you update a non-@State variable in SwiftUI?
Given a SwiftUI view with a normal variable (not marked with @State), what happens if you change its value inside the view?
iOS Swift
struct ContentView: View {
var count = 0
var body: some View {
VStack {
Text("Count: \(count)")
Button("Increment") {
// count += 1 // Imagine this line runs
}
}
}
}Attempts:
2 left
💡 Hint
Think about what SwiftUI watches to know when to redraw.
✗ Incorrect
SwiftUI only tracks changes to variables marked with @State or other reactive wrappers. Normal variables changing do not trigger UI updates.
🔧 Debug
advancedWhy does this SwiftUI view not update the UI?
Look at this SwiftUI code. Why does pressing the button not update the displayed count?
iOS Swift
struct ContentView: View {
var count = 0
var body: some View {
VStack {
Text("Count: \(count)")
Button("Increment") {
count += 1
}
}
}
}Attempts:
2 left
💡 Hint
Check how the variable is declared and if SwiftUI watches it.
✗ Incorrect
Without @State, SwiftUI does not track changes to 'count', so the UI does not refresh when it changes.
expert
How does state affect navigation in SwiftUI?
In SwiftUI, you want to navigate to a new screen when a button is pressed by changing a @State variable. Which code snippet correctly triggers navigation based on state?
iOS Swift
struct ContentView: View {
@State private var showDetail = false
var body: some View {
NavigationView {
VStack {
Button("Show Detail") {
showDetail = true
}
NavigationLink(destination: Text("Detail View"), isActive: $showDetail) {
EmptyView()
}
}
}
}
}Attempts:
2 left
💡 Hint
Think about how NavigationLink uses bindings to control navigation.
✗ Incorrect
NavigationLink with an isActive binding to a @State variable lets SwiftUI navigate automatically when the state changes.
