Skip to content

Instantly share code, notes, and snippets.

@hsavit1
Forked from jtbandes/fast-enumeration.swift
Created December 11, 2015 05:12
Show Gist options
  • Select an option

  • Save hsavit1/5c400c4ea6e34dc3b532 to your computer and use it in GitHub Desktop.

Select an option

Save hsavit1/5c400c4ea6e34dc3b532 to your computer and use it in GitHub Desktop.
// Before realizing that NSFastGenerator exists...
func enumerate(c: NSFastEnumeration) -> SequenceOf<AnyObject> {
return SequenceOf<AnyObject> { () -> GeneratorOf<AnyObject> in
let bufSize = 16
var objects = UnsafeMutablePointer<AnyObject?>.alloc(bufSize)
var state = NSFastEnumerationState()
var currentCount = 0
var currentIndex = 0
return GeneratorOf<AnyObject> {
if currentIndex >= currentCount {
// Enumerate the next chunk of items
currentIndex = 0
currentCount = c.countByEnumeratingWithState(&state, objects: AutoreleasingUnsafeMutablePointer(objects), count: bufSize)
if currentCount == 0 {
// Iteration is finished.
objects.dealloc(bufSize)
objects = nil
return nil
}
}
return state.itemsPtr[currentIndex++]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment