Skip to content

Commit 0b70cac

Browse files
committed
Add labels to the tuples produced by chunked(on:)
Label the tuple produced by `chunked(on:)` with `subject` and `chunk`. This will improve the legibility of code downstream of the said function. For example, when providing an identifier for SwiftUI's `ForEach`: ``` -ForEach(chunkedByDate, id: \.0) { date, items in +ForEach(chunkedByDate, id: \.subject) { date, items in ``` This aligns `ChunkedOnCollection` with the `IndexedCollection`, which specifies `index` and `element` as well as the built-in `EnumeratedSequence` (specifying `offset` and `element`). The introduction of the label will have no effect on existing code, because the index-based address of the tuple component will remain unchanged and absent labels will be inferred.
1 parent 0e939e7 commit 0b70cac

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

Sources/Algorithms/Chunked.swift

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,7 @@ public struct ChunkedOnCollection<Base: Collection, Subject: Equatable> {
162162

163163
extension ChunkedOnCollection: Collection {
164164
public typealias Index = ChunkedByCollection<Base, Subject>.Index
165+
public typealias Element = (subject: Subject, chunk: Base.SubSequence)
165166

166167
@inlinable
167168
public var startIndex: Index {
@@ -174,7 +175,7 @@ extension ChunkedOnCollection: Collection {
174175
}
175176

176177
@inlinable
177-
public subscript(position: Index) -> (Subject, Base.SubSequence) {
178+
public subscript(position: Index) -> Element {
178179
let subsequence = chunked[position]
179180
// swift-format-ignore: NeverForceUnwrap
180181
// Chunks are never empty, so `.first!` is safe.
@@ -509,7 +510,7 @@ extension Collection {
509510
@inlinable
510511
public func chunked<Subject: Equatable>(
511512
on projection: (Element) throws -> Subject
512-
) rethrows -> [(Subject, SubSequence)] {
513+
) rethrows -> [ChunkedOnCollection<Self, Subject>.Element] {
513514
guard !isEmpty else { return [] }
514515
var result: [(Subject, SubSequence)] = []
515516

Tests/SwiftAlgorithmsTests/ChunkedTests.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,16 @@ final class ChunkedTests: XCTestCase {
7171
IndexValidator().validate(lazyChunks)
7272
}
7373

74+
func testChunkedOnLabels() {
75+
let arrayChunks: Array = fruits.chunked(on: { $0.first })
76+
XCTAssert(arrayChunks.first!.0 == arrayChunks.first!.subject)
77+
XCTAssert(arrayChunks.first!.1 == arrayChunks.first!.chunk)
78+
79+
let lazyChunks = fruits.lazy.chunked(on: { $0.first })
80+
XCTAssert(lazyChunks.first!.0 == lazyChunks.first!.subject)
81+
XCTAssert(lazyChunks.first!.1 == lazyChunks.first!.chunk)
82+
}
83+
7484
func testChunkedBy() {
7585
validateFruitChunks(fruits.chunked(by: { $0.first == $1.first }))
7686

0 commit comments

Comments
 (0)