Created
February 6, 2023 21:13
-
-
Save leptos-null/e521cbd4a8246ea824d823fc398ba255 to your computer and use it in GitHub Desktop.
SwiftUI ForEach initializers that create enumerated elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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