Create a gist now

Instantly share code, notes, and snippets.

// 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