简体   繁体   English

SwiftUI 在 Foreach 中得到 position

[英]SwiftUI get position in Foreach

I am relatively new to SwiftUI, and I have come across a problem.我对 SwiftUI 比较陌生,遇到了一个问题。

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.我已经在数组 +1 处尝试了一个 @state 变量,但 Swiftui 不允许我这样做,因为这不是一个视图。 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.我也不能让 indices() 或 enumerated() 工作,我不能在结构中使用 ID,因为它不是一个范围或 int object。

You should use .enumerated() , with the id as \.element.id .您应该使用.enumerated() ,其id\.element.id

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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