Bird
0
0

Given the struct below, which SwiftUI code correctly displays a list of User instances using ForEach inside a List?

hard📝 Application Q8 of 15
iOS Swift - Lists and Data Display
Given the struct below, which SwiftUI code correctly displays a list of User instances using ForEach inside a List?
struct User: Identifiable {
  let id: UUID
  let username: String
}

let users = [User(id: UUID(), username: "john"), User(id: UUID(), username: "jane")]
AList { ForEach(users) { Text($0.username) } }
BList { ForEach(users, id: \.username) { user in Text(user.username) } }
CList { ForEach(users, id: \.id) { user in Text(user.username) } }
DList { ForEach(users) { user in Text(user.username) } }
Step-by-Step Solution
Solution:
  1. Step 1: Check Identifiable conformance

    The User struct conforms to Identifiable via id property.
  2. Step 2: ForEach usage

    When data conforms to Identifiable, ForEach can be used without specifying an id.
  3. Step 3: Analyze options

    List { ForEach(users) { user in Text(user.username) } } correctly uses ForEach(users). List { ForEach(users, id: \.username) { user in Text(user.username) } } incorrectly uses username as id. List { ForEach(users, id: \.id) { user in Text(user.username) } } is redundant but valid. List { ForEach(users) { Text($0.username) } } uses shorthand but is less clear.
  4. Final Answer:

    List { ForEach(users) { user in Text(user.username) } } -> Option D
  5. Quick Check:

    Use ForEach with Identifiable data without id param [OK]
Quick Trick: Use ForEach with Identifiable data without id param [OK]
Common Mistakes:
  • Specifying id when Identifiable is already conformed
  • Using non-unique properties as id

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes