Skip to content

Instantly share code, notes, and snippets.

@acalism
Created July 5, 2017 07:57
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 acalism/440f58badff851af49aae45c8b7bb510 to your computer and use it in GitHub Desktop.
Save acalism/440f58badff851af49aae45c8b7bb510 to your computer and use it in GitHub Desktop.
如何枚举enum类型的所有case
protocol EnumCollection : Hashable {}
extension EnumCollection {
static func cases() -> AnySequence<Self> {
typealias S = Self
return AnySequence { () -> AnyIterator<S> in
var raw = 0
return AnyIterator {
let current : Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: S.self, capacity: 1) { $0.pointee } }
guard current.hashValue == raw else { return nil }
raw += 1
return current
}
}
}
}
enum E : EnumCollection {
case A, B, C
}
// example
Array(E.cases()) // [A, B, C]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment