我是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)
答案 0 :(得分:1)
在indices
的变体中,您应将self
用作id
ForEach(self.postViewModel.posts.indices, id: \.self) { post in
可能同时具有两者
ForEach(Array(self.postViewModel.posts.enumerated()),
id: \.1.postId) { (index, post) in