2

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)

1 Answer 1

10

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.