How to get the previous element in a SwiftUI ForEach?

Viewed 693

I have a ForEach like this in SwiftUI:

ForEach(entries) { (e: MyType) in
   NavigationLinkItem(entry: e)
}

now I need to also pass the previous Entry to my View (NavigationLinkItem) to do something like this:

ForEach(entries) { (e: MyType) in
   NavigationLinkItem(entry: e, sucessor: ...)
}

How to realise that?

2 Answers

To keep ForEach dynamic, find below possible approach (assuming MyType is Identifiable, and successor is optional)

ForEach(Array(entries.enumerated()), id: \.1.id) { (index, e) in
   NavigationLinkItem(entry: e, sucessor: (index == 0 ? nil : self.entries[index - 1]))
}

I would do this. Assuming you need to pass an object to your successor. I would suggest you make successor an optional

ForEach((0...entries.count-1), id:\.self) {i in 
   NavigationLinkItem(entry: self.entries[i], sucessor: i == 0 ? self.entries[0] : self.entries[i-1])
}

EDIT: As suggested in the comments, its better to use indices than count.

ForEach((0...entries.indices), id:\.self) {i in 
   NavigationLinkItem(entry: self.entries[i], sucessor: i == self.entries.startIndex ? self.entries.first : self.entries[i-1])
}
Related