我是 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
关于ios - 在 ForEach 循环 SwiftUI 中使用索引获取索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63846503/