4
4
[ Tests] ( https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/ChunkedTests.swift )]
5
5
6
6
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 ` .
8
11
9
12
There are two variations of the ` chunked ` method: ` chunked(by:) ` and
10
13
` chunked(on:) ` . ` chunked(by:) ` uses a binary predicate to test consecutive
@@ -26,17 +29,32 @@ let chunks = names.chunked(on: \.first!)
26
29
// [["David"], ["Kyle", "Karoy"], ["Nate"]]
27
30
```
28
31
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.
34
50
35
51
``` swift
36
52
c.elementsEqual (c.chunked (... ).joined ())
37
53
// true
38
54
```
39
55
56
+ Check the [ proposal] [ proposal ] detailed design section for more info.
57
+
40
58
[ proposal ] : https://github.com/apple/swift-evolution/pull/935
41
59
42
60
## Detailed Design
0 commit comments