Skip to content

Commit 3092eb1

Browse files
[Chucked] Add chunks(ofCount:) information on the Chunked guides
1 parent e0fed41 commit 3092eb1

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

Guides/Chunked.md

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@
44
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ChunkedTests.swift)]
55

66
Break a collection into subsequences where consecutive elements pass a binary
7-
predicate, or where all elements in each chunk project to the same value.
7+
predicate, or where all elements in each chunk project to the same value.
8+
9+
Also, includes a `chunks(ofCount:)` that breaks a collection into subsequences
10+
of a given `count`.
811

912
There are two variations of the `chunked` method: `chunked(by:)` and
1013
`chunked(on:)`. `chunked(by:)` uses a binary predicate to test consecutive
@@ -26,17 +29,32 @@ let chunks = names.chunked(on: \.first!)
2629
// [["David"], ["Kyle", "Karoy"], ["Nate"]]
2730
```
2831

29-
These methods are related to the [existing SE proposal][proposal] for chunking a
30-
collection into subsequences of a particular size, potentially named something
31-
like `chunked(length:)`. Unlike the `split` family of methods, the entire
32-
collection is included in the chunked result — joining the resulting chunks
33-
recreates the original collection.
32+
The `chunks(ofCount:)` takes a `count` parameter (required to be > 0) and separates
33+
the collection into `n` chunks of this given count. If the `count` parameter is
34+
evenly divided by the count of the base `Collection` all the chunks will have
35+
the count equals to the parameter. Otherwise, the last chunk will contain the
36+
remaining elements.
37+
38+
```swift
39+
let names = ["David", "Kyle", "Karoy", "Nate"]
40+
let evenly = names.chunks(ofCount: 2)
41+
// equivalent to [["David", "Kyle"], ["Karoy", "Nate"]]
42+
43+
let remaining = names.chunks(ofCount: 3)
44+
// equivalent to [["David", "Kyle", "Karoy"], ["Nate"]]
45+
```
46+
47+
The `chunks(ofCount:)` is the method of the [existing SE proposal][proposal].
48+
Unlike the `split` family of methods, the entire collection is included in the
49+
chunked result — joining the resulting chunks recreates the original collection.
3450

3551
```swift
3652
c.elementsEqual(c.chunked(...).joined())
3753
// true
3854
```
3955

56+
Check the [proposal][proposal] detailed design section for more info.
57+
4058
[proposal]: https://github.com/apple/swift-evolution/pull/935
4159

4260
## Detailed Design

0 commit comments

Comments
 (0)