Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
extension Array {
func forEachSlice(sliceSize: Int, block: [Element] -> Void) {
guard sliceSize > 0 && self.count > 0 else {
return
}
var currentSlice = [Element]()
defer {
if !currentSlice.isEmpty {
block(currentSlice)
}
}
for element in self {
currentSlice.append(element)
if currentSlice.count >= sliceSize {
block(currentSlice)
currentSlice.removeAll(keepCapacity: true)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment