Skip to content

Instantly share code, notes, and snippets.

@shmidt
Last active March 21, 2019 21:43
Show Gist options
  • Save shmidt/a157e46828a0c59a93815af51cb1140b to your computer and use it in GitHub Desktop.
Save shmidt/a157e46828a0c59a93815af51cb1140b to your computer and use it in GitHub Desktop.
For loop using batches
import Foundation
public extension Array {
/**
Loops through array by batches
- Parameter batchSize: Size of the batch
- batch: Current batch elements
- currentNo: Current batch number
- totalCount: Batches amount
**/
func forEachBatch(size batchSize: Int, _ transform: (_ batch: [Element], _ currentNo: Int, _ totalCount: Int) throws -> Void) rethrows{
let count = self.count
// Determine the total number of batches.
var numBatches = count / batchSize
numBatches += count % batchSize > 0 ? 1 : 0
for batchNumber in 0 ..< numBatches {
// Determine the range for this batch.
let batchStart = batchNumber * batchSize
let batchEnd = batchStart + Swift.min(batchSize, count - batchNumber * batchSize)
let range = batchStart..<batchEnd
// Create a batch for this range.
let batch = Array(self[range])
try autoreleasepool(invoking: { () -> Void in
try transform(batch, batchNumber, numBatches)
})
}
}
}
@shmidt
Copy link
Author

shmidt commented Mar 20, 2019

array.forEachBatch(size: batchSize) { (batch, currentNo, totalNo) in
            print(batch, currentNo, totalNo)
 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment