Bird
0
0

What is the issue with this SwiftUI code snippet?

medium📝 Debug Q6 of 15
iOS Swift - Lists and Data Display
What is the issue with this SwiftUI code snippet?
let scores = [100, 200, 300]

List {
  ForEach(scores) { score in
    Text("Score: \(score)")
  }
}
AList cannot contain ForEach directly.
BThe Text view syntax is incorrect.
CThe array elements are Ints and ForEach requires an id or Identifiable conformance.
DThe scores array should be declared as a @State variable.
Step-by-Step Solution
Solution:
  1. Step 1: Check ForEach requirements

    ForEach requires either data conforming to Identifiable or an explicit id parameter.
  2. Step 2: Analyze the data type

    Here, scores is an array of Ints, which do not conform to Identifiable.
  3. Step 3: Identify the error

    Missing id: \.self causes a compile-time error.
  4. Final Answer:

    The array elements are Ints and ForEach requires an id or Identifiable conformance. -> Option C
  5. Quick Check:

    ForEach over Int array needs id: \.self [OK]
Quick Trick: ForEach over Int array needs id: \.self [OK]
Common Mistakes:
  • Assuming Ints are Identifiable by default
  • Ignoring the need for id parameter

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes