Skip to content

Commit dd1fdc4

Browse files
committed
Update initializers
1 parent 8aba5f9 commit dd1fdc4

File tree

1 file changed

+39
-6
lines changed

1 file changed

+39
-6
lines changed

Sources/swiftui-indexed-for-each/swiftui_indexed_for_each.swift

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,35 @@
11
import SwiftUI
22

3-
public struct IndexedForEach<Element, Content>: View where Content: View {
3+
public struct IndexedForEach<Element, ID: Hashable, Content: View>: View {
44

5-
let data: Array<Element>
5+
private let data: [Element]
66

7-
let content: (Array<Element>.Index, Element) -> Content
7+
private let content: (Array<Element>.Index, Element) -> Content
88

9-
public init(data: Array<Element>, @ViewBuilder content: @escaping (Array<Element>.Index, Element) -> Content) {
9+
private let id: KeyPath<IndexedArray<Element>.Element, ID>
10+
11+
public init(
12+
_ data: [Element],
13+
@ViewBuilder content: @escaping (Array<Element>.Index, Element) -> Content
14+
) where Element: Identifiable, ID == Element.ID {
15+
16+
self.data = data
17+
self.content = content
18+
self.id = \.1.id
19+
}
20+
21+
public init(
22+
_ data: [Element],
23+
id: KeyPath<Element, ID>,
24+
@ViewBuilder content: @escaping (Array<Element>.Index, Element) -> Content
25+
) where Data: RandomAccessCollection, ID: Hashable {
1026
self.data = data
27+
self.id = (\IndexedArray<Element>.Element.1).appending(path: id)
1128
self.content = content
1229
}
1330

1431
public var body: some View {
15-
ForEach(IndexedArray.init(base: data), id: \.0) { e in
32+
ForEach(IndexedArray.init(base: data), id: id) { e in
1633
content(e.0, e.1)
1734
}
1835
}
@@ -70,10 +87,26 @@ struct IndexedArray<SourceElement>: RandomAccessCollection {
7087

7188
}
7289

90+
#if DEBUG
91+
92+
struct Item: Identifiable {
93+
let id: Int
94+
}
95+
7396
#Preview {
7497
VStack {
75-
IndexedForEach(data: [1, 2, 3]) { index, element in
98+
IndexedForEach([1, 2, 3], id: \.self) { index, element in
99+
Text("\(index): \(element)")
100+
}
101+
}
102+
}
103+
104+
#Preview {
105+
VStack {
106+
IndexedForEach.init([Item(id: 0)]) { index, element in
76107
Text("\(index): \(element)")
77108
}
78109
}
79110
}
111+
112+
#endif

0 commit comments

Comments
 (0)