Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// generate sequence of all values from arbitrary Enum type
- /// Works with Swift 1.1
- /// No support for Enum with associated values.
- func iterateEnum<T: Hashable>(_: T.Type) -> GeneratorOf<T> {
- var cast: (Int -> T)!
- switch sizeof(T) {
- case 0: return GeneratorOf(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()
- }
- var i = 0
- return GeneratorOf {
- let next = cast(i)
- return next.hashValue == i++ ? next : nil
- }
- }
- // Example usage:
- enum Foo: String {
- case A = "A", B = "B", C = "C", D = "D", E = "E"
- }
- for e in iterateEnum(Foo) {
- println(e.rawValue)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement