Advertisement
Guest User

Untitled

a guest
Mar 31st, 2015
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. /// generate sequence of all values from arbitrary Enum type
  2. /// Works with Swift 1.1
  3. /// No support for Enum with associated values.
  4. func iterateEnum<T: Hashable>(_: T.Type) -> GeneratorOf<T> {
  5. var cast: (Int -> T)!
  6. switch sizeof(T) {
  7. case 0: return GeneratorOf(GeneratorOfOne(unsafeBitCast((), T.self)))
  8. case 1: cast = { unsafeBitCast(UInt8(truncatingBitPattern: $0), T.self) }
  9. case 2: cast = { unsafeBitCast(UInt16(truncatingBitPattern: $0), T.self) }
  10. case 4: cast = { unsafeBitCast(UInt32(truncatingBitPattern: $0), T.self) }
  11. case 8: cast = { unsafeBitCast(UInt64($0), T.self) }
  12. default: fatalError()
  13. }
  14.  
  15. var i = 0
  16. return GeneratorOf {
  17. let next = cast(i)
  18. return next.hashValue == i++ ? next : nil
  19. }
  20. }
  21.  
  22. // Example usage:
  23.  
  24. enum Foo: String {
  25. case A = "A", B = "B", C = "C", D = "D", E = "E"
  26. }
  27.  
  28. for e in iterateEnum(Foo) {
  29. println(e.rawValue)
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement