Skip to content

Instantly share code, notes, and snippets.

@kateinoigakukun
Created April 2, 2017 08:22
Show Gist options
  • Save kateinoigakukun/8711431af63d06cf91352df8f0a4923a to your computer and use it in GitHub Desktop.
Save kateinoigakukun/8711431af63d06cf91352df8f0a4923a to your computer and use it in GitHub Desktop.
forの部分をきれいに書けない #CodePiece
protocol EnumExtension {}
extension EnumExtension where Self: Hashable {
static var all: [Self] {
var result: [Self] = []
for i in 0..<0xff*MemoryLayout<Self>.size {
var n = i
let ptr = withUnsafePointer(to: &n) { UnsafeRawPointer($0) }
.bindMemory(to: Self.self, capacity: MemoryLayout<Self>.size)
if ptr.pointee.hashValue != n { break }
result.append(ptr.pointee)
}
return result
}
}
enum Fruit: EnumExtension {
case peach
case apple
case grape
}
Fruit.all // [peach, apple, grape]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment