Last active
March 21, 2019 21:43
-
-
Save shmidt/a157e46828a0c59a93815af51cb1140b to your computer and use it in GitHub Desktop.
For loop using batches
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}) | |
} | |
} | |
} |
Author
shmidt
commented
Mar 20, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment