Last active
August 29, 2015 14:08
-
-
Save MartinJNash/f0974bc10f89563d6e9a to your computer and use it in GitHub Desktop.
Batching Swift Arrays
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
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