Created
April 2, 2017 08:22
-
-
Save kateinoigakukun/8711431af63d06cf91352df8f0a4923a to your computer and use it in GitHub Desktop.
forの部分をきれいに書けない #CodePiece
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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