Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the previous element in a SwiftUI ForEach?

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?

like image 555
gurehbgui Avatar asked Sep 12 '25 02:09

gurehbgui


1 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]))
}
like image 127
Asperi Avatar answered Sep 13 '25 17:09

Asperi