Chunking
Break collections into consecutive chunks by length, count, or based on closure-based logic.
Overview
Chunking is the process of breaking a collection into consecutive subsequences, without dropping or duplicating any of the collection’s elements. After chunking a collection, joining the resulting subsequences produces the original collection of elements, unlike splitting, which consumes the separator element(s).
let names = ["Ji-sun", "Jin-su", "Min-jae", "Young-ho"]
let evenlyChunked = names.chunks(ofCount: 2)
// ~ [["Ji-sun", "Jin-su"], ["Min-jae", "Young-ho"]]
let chunkedByFirstLetter = names.chunked(on: \.first)
// equivalent to [("J", ["Ji-sun", "Jin-su"]), ("M", ["Min-jae"]), ("Y", ["Young-ho"])]
Chunking a Collection by Count
func chunks(ofCount: Int
) -> ChunksOfCountCollection<Self> Returns a collection of subsequences, each with up to the specified length.
func evenlyChunked(in: Int
) -> EvenlyChunkedCollection<Self> Returns a collection of evenly divided consecutive subsequences of this collection.
Chunking a Collection by Predicate
func chunked(by: (Element, Element) throws -> Bool
) rethrows -> [SubSequence] Returns a collection of subsequences of this collection, chunked by the given predicate.
func chunked(by: @escaping (Element, Element) -> Bool
) -> ChunkedByCollection<Elements, Element> Returns a lazy collection of subsequences of this collection, chunked by the given predicate.
Chunking a Collection by Subject
func chunked<Subject>(on: (Element) throws -> Subject
) rethrows -> [(Subject, SubSequence)] Returns a collection of subsequences of this collection, chunked by grouping elements that project to equal values.
func chunked<Subject>(on: @escaping (Element) -> Subject
) -> ChunkedOnCollection<Elements, Subject> Returns a lazy collection of subsequences of this collection, chunked by grouping elements that project to equal values.
Supporting Types
struct ChunkedByCollection<Base, Subject>
A collection wrapper that breaks a collection into chunks based on a predicate.
struct ChunkedOnCollection<Base, Subject>
A collection wrapper that breaks a collection into chunks based on a predicate.
struct ChunksOfCountCollection<Base>
A collection that presents the elements of its base collection in
SubSequence
chunks of any given count.struct EvenlyChunkedCollection<Base>
A collection wrapper that evenly breaks a collection into a given number of chunks.