Learn Courses My Dashboard

When to use (id: \.self) in ForEach/List command plz?

Hello. Can anyone explain to me that in which case we declare the “id: .self” in ForEach/List Command? from module 1 and module 2 (Foundation), I see Chris declare in two way but I don’t know why

for Example:
ContentView1:
struct Detail: View {
var newUI:card
var body: some View {
ScrollView{
Text(newUI.name)
ForEach(newUI.quotes, id: .self) { t in

  •            Text(t)*                
          }
      }         
    

}
}

ContentView2:

struct ContentView: View {
@ObservedObject var model = cardView()

var body: some View {
    ScrollView{
    *ForEach (model.cardArray){ t in*
  •        *
    
  •            Image(t.image)*
      }
    
    }

Thank you so much

You use the ForEach version with an explicit id parameter when the items you are looping over do not have an id property.

If the items in the array you are looping through have an id property, then ForEach will use that and you do not have to explicitly tell it what to use as the id.

2 Likes

thanks for your kindly reply bro