Mohamed
Mohamed

Reputation: 59

Using Indices to get Index in a ForEach loop SwiftUI

I am new to SwiftUI and I am trying to get the index for the following ForEach Loop

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

I have tried using indices as in the following:

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

but I got this error

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

I have also tried using index but obviously it wouldn't work since index isn't in the loop

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)

Upvotes: 2

Views: 9664

Answers (1)

Asperi
Asperi

Reputation: 257493

In the variant of indices, you should use self as id

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

Possible variant to have both

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

Upvotes: 10

Related Questions