Skip to content

Instantly share code, notes, and snippets.

@nashysolutions
Created March 18, 2021 22:46
Show Gist options
  • Save nashysolutions/2a76520192bc282d4ffa4faa70bd352f to your computer and use it in GitHub Desktop.
Save nashysolutions/2a76520192bc282d4ffa4faa70bd352f to your computer and use it in GitHub Desktop.
How to pass a binding from within ForEach
extension ReportStore where Report: Identifiable {
func binding(for report: Report) -> Binding<Report> {
let index = fetchedItems.firstIndex(where: { $0.id == report.id } )!
return Binding(
get: { self.fetchedItems[index] },
set: { self.fetchedItems[index] = $0 }
)
}
}
struct ReportsView: View {
@StateObject var store: ReportStore
var body: some View {
List {
ForEach(store.fetchedItems) { report in
NavigationLink(
destination: ReportView(report: store.binding(for: report)),
label: {
ReportCell(report: report)
})
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment