Skip to content

Commit e6b0eb4

Browse files
authored
Update README.md
1 parent 6c02326 commit e6b0eb4

File tree

1 file changed

+38
-15
lines changed

1 file changed

+38
-15
lines changed

README.md

Lines changed: 38 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,46 @@
1-
# IndexedForEach
1+
# IndexedCollection
2+
3+
A wrapper collection that provides items with its index using underlying collection without allocation.
24

35
## Motivation
4-
The purpose of using IndexedForEach is to read array's element and its index in safe way.
5-
As using `.enumerated()` is unsafe way because of the index does not always start from 0.
6+
7+
In SwiftUI, we might use these following technique for using index in `ForEach`.
8+
9+
```swift
10+
ForEach(Array(array.enumerated()), id: \.offset) { ... }
11+
```
12+
13+
```swift
14+
ForEach(zip(array.indices, array), id: \.0) { ... }
15+
```
16+
17+
There is downside like followings:
18+
- Creating new buffer by making new collection
19+
- `enumerated` provides index from 0 so that makes wrong access on using slice.
620

721
## Usage
822

23+
```swift
24+
#Preview {
25+
VStack {
26+
ForEach.init(IndexedCollection([1, 2, 3, 4, 5]), id: \.index, content: { e in
27+
Text("\(e.index): \(e.value)")
28+
})
29+
}
30+
}
931
```
10-
import SwiftUI
11-
12-
struct ContentView: View {
13-
let numbers = [1, 2, 3]
14-
15-
var body: some View {
16-
VStack {
17-
IndexedForEach(numbers) { index, element in
18-
Text("\(index): \(element)")
19-
}
20-
}
21-
}
32+
33+
```swift
34+
struct IdentifiableItem: Identifiable {
35+
let id: String
36+
let value: UUID = .init()
37+
}
38+
39+
#Preview {
40+
VStack {
41+
ForEach.init(IndexedCollection(["a", "b", "c", "d", "e"].map(IdentifiableItem.init(id:))), content: { e in
42+
Text("\(e.index): \(e.value)")
43+
})
44+
}
2245
}
2346
```

0 commit comments

Comments
 (0)