Skip to content

Instantly share code, notes, and snippets.

@krzyzanowskim
Last active November 26, 2015 22:21
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save krzyzanowskim/ae4f2c3b35c72a23f220 to your computer and use it in GitHub Desktop.
Save krzyzanowskim/ae4f2c3b35c72a23f220 to your computer and use it in GitHub Desktop.
// http://blog.krzyzanowskim.com
import Cocoa
struct ChunkSequence<Element>: SequenceType {
let chunkSize: Array<Element>.Index
let collection: Array<Element>
func generate() -> AnyGenerator<ArraySlice<Element>> {
var offset:Array<Element>.Index = collection.startIndex
return anyGenerator {
let result = self.collection[offset..<offset.advancedBy(self.chunkSize, limit: self.collection.endIndex)]
offset += result.count
return result.count > 0 ? result : nil
}
}
}
extension Array {
func slice(every every: Index) -> ChunkSequence<Element> {
return ChunkSequence(chunkSize: every, collection: self)
}
}
var πŸŽ‚ = ["🍰","🍰","🍰","🍰","🍰"]
for 🍰 in πŸŽ‚.slice(every: 2) {
print(🍰)
}
var array:Array<Int> = [1,2,3,4,5]
for slice in array.slice(every: 2) {
print(slice)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment