OneBite.Dev - Coding blog in a bite size

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:

  1. We begin by defining a function splitArray(array:subSize:) that will take an array of integers array and an integer subSize to determine the size of your smaller arrays, or sub-arrays.

  2. 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.

  3. Next, we define an empty array result to hold our newly created sub-arrays.

  4. We start a while loop that will run until our dataArray is empty. During each iteration of the loop, we’re taking the first subSize elements from the dataArray and creating a sub-array.

  5. The subArray is then appended to our result array. We then remove the just used elements from dataArray starting from the 0th element to the subSize element. This is so that in the next iteration of the loop, we move on to a new sub-array.

  6. 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.

swift