Split an array into chunks in Swift

In this tutorial, we will learn how to divide an array into smaller chunks of fixed size. We can do this easily by creating a function. But first, let’s dive into the example-

Array-

[1,2,3,4,5,6,7,8,9,10]

Chunks of length 2:

[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]

Our output should look similar.

As for now, we have clearly discussed what is our task and how does our output look like. The flow of the program would be to create a function that will-

  1. Take size as a parameter.
  2. Take elements from 0.
  3. Map into chunks of 2.
  4. Return the resultant array.

We will just create an array of the above 10 elements and pass it to the function and the function will do its job.

extension Array {
    func chunk(into size: Int) -> [[Element]] {
        return stride(from: 0, to: count, by: size).map {
            Array(self[$0 ..< Swift.min($0 + size, count)])
        }
    }
}
let integer = Array(1...10)
let array = integer.chunk(into: 2)
print(array)

Output-

[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]

Here we have created a function to divide the entire array into chunks of size two. I hope you liked this tutorial. Thanks for reading!

Leave a Reply

Your email address will not be published. Required fields are marked *