Skip to content

Instantly share code, notes, and snippets.

@shaps80
Created March 8, 2016 20:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaps80/d1ea6dc45d330c1e16b2 to your computer and use it in GitHub Desktop.
Save shaps80/d1ea6dc45d330c1e16b2 to your computer and use it in GitHub Desktop.
func enumIterator<T: Hashable>(_: T.Type) -> AnyGenerator<T> {
var cast: (Int -> T)!
switch sizeof(T) {
case 0: return anyGenerator(GeneratorOfOne(unsafeBitCast((), T.self)))
case 1: cast = { unsafeBitCast(UInt8(truncatingBitPattern: $0), T.self) }
case 2: cast = { unsafeBitCast(UInt16(truncatingBitPattern: $0), T.self) }
case 4: cast = { unsafeBitCast(UInt32(truncatingBitPattern: $0), T.self) }
case 8: cast = { unsafeBitCast(UInt64($0), T.self) }
default: fatalError("cannot be here")
}
var i = 0
return anyGenerator {
let next = cast(i)
return next.hashValue == i++ ? next : nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment