Swift chunked collection batches of fixed size
Swift
import Foundation
func chunked<C: Collection>(_ items: C, size: Int) -> [[C.Element]] {
guard size > 0 else { return [] }
var batches: [[C.Element]] = []
var start = items.startIndex
while start < items.endIndex {
let end = items.index(start, offsetBy: size, limitedBy: items.endIndex) ?? items.endIndex
batches.append(Array(items[start..<end]))
start = end
}
return batches
}