Skip to content

Instantly share code, notes, and snippets.

@MartinJNash
Last active August 29, 2015 14:08
Show Gist options
  • Save MartinJNash/f0974bc10f89563d6e9a to your computer and use it in GitHub Desktop.
Save MartinJNash/f0974bc10f89563d6e9a to your computer and use it in GitHub Desktop.
Batching Swift Arrays
extension Array {
func elementsInRange(start: Int, length: Int) -> Slice<T>? {
if start >= self.count {
return nil
}
var lastIndex = start + length
if start + length > self.count {
lastIndex = self.count
}
if lastIndex == start {
return nil
}
return self[ start ..< lastIndex ]
}
func enumerateBatchesOfSize(size: Int, block: (Slice<T>)->()) {
var startIndex: Int = 0
while let sub = self.elementsInRange(startIndex, length: size) {
block(sub)
startIndex += size
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment