Skip to content

Instantly share code, notes, and snippets.

@leptos-null
Created February 6, 2023 21:13
Show Gist options
  • Save leptos-null/e521cbd4a8246ea824d823fc398ba255 to your computer and use it in GitHub Desktop.
Save leptos-null/e521cbd4a8246ea824d823fc398ba255 to your computer and use it in GitHub Desktop.
SwiftUI ForEach initializers that create enumerated elements
import SwiftUI
extension ForEach {
init<Base: Sequence>(enumerated base: Base, @ViewBuilder content: @escaping (Data.Element) -> Content) where Data == Array<EnumeratedSequence<Base>.Element>, ID == Base.Element, Content: View, ID: Identifiable {
self.init(Array(base.enumerated()), id: \.element, content: content)
}
init<Base: Sequence>(enumerated base: Base, id: KeyPath<Base.Element, ID>, @ViewBuilder content: @escaping (Data.Element) -> Content) where Data == Array<EnumeratedSequence<Base>.Element>, Content: View {
let basePath: KeyPath<EnumeratedSequence<Base>.Element, Base.Element> = \.element
self.init(Array(base.enumerated()), id: basePath.appending(path: id), content: content)
}
}
// common usage:
//
// ForEach(enumerated: ["a", "b", "c"], id: \.self) { offset, element in
// if offset != 0 {
// Divider()
// }
// Text(element)
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment