In this post, We will share a swift program to split an array into chunks with an example and real-time output. This is a very basic program in Swift programming language. If you are Swift beginners or want to start learning Swift programming language, then this program will help you to understand the basic Swift programming.
In the below example we have used
chunked() function to split an array into chunks of the size you specify.
Copy the below program and create a file named “ArrayChunks.swift” and execute it.
func chunked(into size: Int) -> [[Element]]
return stride(from: 0, to: count, by: size).map
Array(self[$0 ..< Swift.min($0 + size, count)])
Let assume you have an array of 50 elements and you want to split into chunks of 10 elements, then use the below example how you can do this:
let numbers = Array(1,2,3,4,5.....50)
let result = numbers.chunked(into: 10)
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.