Skip to content

Instantly share code, notes, and snippets.

@erica
Last active February 19, 2019 23:10
Show Gist options
  • Save erica/dd1f6616b4124c588cf7 to your computer and use it in GitHub Desktop.
Save erica/dd1f6616b4124c588cf7 to your computer and use it in GitHub Desktop.
func enumCount<EnumType:Hashable>(eType : EnumType.Type) -> Int {
if sizeof(eType) == 0 {return 1} // throw up hands
if sizeof(eType) > 2 {fatalError("too many enumeration cases.")}
let singleByte = sizeof(eType) == 1
let min = singleByte ? 2 : 257
let max = singleByte ? 2 << 8 : 2 << 16
for hashIndex in min..<max {
switch singleByte {
case true:
if unsafeBitCast(UInt8(hashIndex), eType).hashValue == 0 {
return hashIndex
}
case false:
if unsafeBitCast(UInt16(hashIndex), eType).hashValue == 0 {
return hashIndex
}
}
}
return max
}
func members<EnumType:Hashable>(eType:EnumType.Type) -> [EnumType] {
var enumMembers = [EnumType]()
let singleByte = sizeof(eType) == 1
for index in 0..<enumCount(EnumType) {
switch singleByte {
case true:
let member = unsafeBitCast(UInt8(index), EnumType.self)
enumMembers.append(member)
case false:
let member = unsafeBitCast(UInt16(index), EnumType.self)
enumMembers.append(member)
}
}
return enumMembers
}
enum Planets : Int {case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Neptune, Uranus, Pluto}
enum Foo : Int {case i = 1, j = 5, k = 9}
enum Coin {case Heads, Tails}
enum Quark: String {case Up, Down, Top, Bottom, Strange, Charmed}
print(members(Planets))
print(members(Foo))
print(members(Coin))
print(members(Quark))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment