Split An Array Into Smaller Arrays In Swift
Code snippet for how to Split An Array Into Smaller Arrays In Swift with sample and detail explanation
When developing in Swift, you may encounter situations where you want to break down an array into smaller parts. This article will show you exactly how you can accomplish this in straightforward, easy-to-follow steps.
Code snippet for Splitting an Array in Swift
Here is a simple Swift function that can help you split your array into smaller ones:
func splitArray(array: [Int], subSize: Int) -> [[Int]] {
var dataArray = array
var result: [[Int]] = []
while !dataArray.isEmpty {
let subArray: [Int] = Array(dataArray[0..<subSize])
result.append(subArray)
dataArray.removeSubrange(0..<subSize)
}
return result
}
let numbers: [Int] = [1, 2, 3, 4, 5, 6, 7, 8]
print(splitArray(array: numbers, subSize: 2))
// Output : [[1, 2], [3, 4], [5, 6], [7, 8]]
Code Explanation for Splitting an Array in Swift
Let’s break down this code to understand how it works:
-
We begin by defining a function
splitArray(array:subSize:)
that will take an array of integersarray
and an integersubSize
to determine the size of your smaller arrays, or sub-arrays. -
We then define
var dataArray
as a mutable copy of our input array. This is important because we need to modify our array during the process. -
Next, we define an empty array
result
to hold our newly created sub-arrays. -
We start a while loop that will run until our
dataArray
is empty. During each iteration of the loop, we’re taking the firstsubSize
elements from thedataArray
and creating a sub-array. -
The
subArray
is then appended to ourresult
array. We then remove the just used elements fromdataArray
starting from the 0th element to thesubSize
element. This is so that in the next iteration of the loop, we move on to a new sub-array. -
Lastly, the function returns
result
, which now contains the smaller sub-arrays.
In the provided example, the numbers
array is split into sub-arrays of size 2. The splitArray function will keep creating these sub-arrays until it has dealt with every element in numbers
, as shown in the printed output.
By adjusting the subSize
, you can control the size of your sub-arrays to fit whatever purpose your particular process has in your application.