在 ForEach 循环 SwiftUI 中使用索引获取索引

Using Indices to get Index in a ForEach loop SwiftUI

我是 SwiftUI 的新手,我正在尝试获取以下 ForEach 循环的索引

ForEach(self.postViewModel.posts, id: \.postId) { post in
                      
                                                       HStack(alignment: .top, spacing: 25) {
                                                           Header(post : post)
                                                           Footer(post: post)
                                                       

我试过如下使用索引:

 ForEach(self.postViewModel.posts.indices, id: \.postId) { post in

但我遇到了这个错误

Value of type 'Range<Array<Post>.Index>.Element' (aka 'Int') has no member 'postId'

我也尝试过使用索引,但显然它不会工作,因为索引不在循环中

ForEach(self.postViewModel.posts, id: \.postId) { post in
                           
                                                           HStack(alignment: .top, spacing: 25) {
                                                               Header(post : post)
                                                               Footer(post: post)
                                                           Text("#\(index)").frame(width: 45, height: 30)

indices 的变体中,您应该使用 self 作为 id

ForEach(self.postViewModel.posts.indices, id: \.self) { post in

可能的变体同时具有两者

ForEach(Array(self.postViewModel.posts.enumerated()), 
    id: \.1.postId) { (index, post) in