简体   繁体   中英

SwiftUI get position in Foreach

I am relatively new to SwiftUI, and I have come across a problem.

I have build this struct for my array:

struct Outfit:Identifiable {
   var id = UUID()
   var user: String
   var amount: Double
   var rating: Double
}

and I can print all the information I need out with:

ForEach(loader.outfitcards) { index  in
   // I need to know if it is the first, second, etc. time it runs
}

But I need to know inside the array how many times the array has already run. I have already tried a @state variable at and then inside the array +1 but Swiftui won't let me do that since that is not a view. Can anyone help me? I also can't get indices() or enumerated() to work and I cant use the ID in the struct because that is not a range or int object.

You should use .enumerated() , with the id as \.element.id .

ForEach(Array(loader.outfitcards.enumerated()), id: \.element.id) { (index: Int, outfit: Outfit) in
    /* ... */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM