Challenge - 5 Problems
SwiftUI List Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β ui_behavior
intermediate2:00remaining
What will this SwiftUI List display?
Consider this SwiftUI code snippet. What will the List show when the app runs?
iOS Swift
struct ContentView: View {
let fruits = ["Apple", "Banana", "Cherry"]
var body: some View {
List {
ForEach(fruits, id: \.self) { fruit in
Text(fruit)
}
}
}
}Attempts:
2 left
π‘ Hint
Think about what ForEach does with an array and the id parameter.
β Incorrect
ForEach iterates over the fruits array and creates a Text view for each fruit. The id: \.self tells SwiftUI to use the string itself as a unique identifier. So the List shows Apple, Banana, and Cherry each on its own row.
π Syntax
intermediate2:00remaining
Identify the syntax error in this ForEach usage
Which option correctly fixes the syntax error in this SwiftUI code?
iOS Swift
struct ContentView: View {
let numbers = [1, 2, 3]
var body: some View {
List {
ForEach(numbers) { number in
Text("\(number)")
}
}
}
}Attempts:
2 left
π‘ Hint
ForEach needs a way to identify each item uniquely when using simple arrays.
β Incorrect
When using ForEach with an array of simple values like Int, you must provide an id parameter to uniquely identify each element. Adding id: \.self fixes the syntax error.
β lifecycle
advanced2:00remaining
What happens if the data array changes in a ForEach List?
If the array used in ForEach changes (items added or removed), what does SwiftUI do to the List?
Attempts:
2 left
π‘ Hint
Think about how SwiftUI reacts to state changes.
β Incorrect
SwiftUI watches the data used in ForEach. When the array changes, SwiftUI updates the List UI automatically to match the new data.
π§ Debug
advanced2:00remaining
Why does this ForEach cause a runtime crash?
This code crashes at runtime. What is the cause?
iOS Swift
struct ContentView: View {
let items = ["A", "B", "A"]
var body: some View {
List {
ForEach(items, id: \.self) { item in
Text(item)
}
}
}
}Attempts:
2 left
π‘ Hint
Check the uniqueness of the id values.
β Incorrect
Using id: \.self means each item must be unique. The array has two "A" strings, causing duplicate id error and crash.
π§ Conceptual
expert2:00remaining
Why use ForEach inside a List instead of just List with data?
Which reason best explains why developers use ForEach inside a List in SwiftUI?
Attempts:
2 left
π‘ Hint
Think about flexibility in building UI rows.
β Incorrect
ForEach lets you customize each rowβs content and layout inside a List. List alone can display simple data but ForEach is needed for complex or dynamic row views.