Created
February 8, 2017 03:46
-
-
Save bradhilton/c58ec6c2d1a68b6de3261322e994aab0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Retrieves and recasts the body of an enum | |
func body<T, U>(of value: inout T) -> U { | |
return withUnsafePointer(to: &value) { | |
$0.withMemoryRebound(to: U.self, capacity: 1) { | |
$0.pointee | |
} | |
} | |
} | |
// For enums with associated values, the case flag is stored in the last byte | |
func flag<T>(of value: inout T) -> UInt8 { | |
let size = MemoryLayout<T>.size | |
return withUnsafePointer(to: &value) { | |
$0.withMemoryRebound(to: UInt8.self, capacity: size) { $0[size - 1] } | |
} | |
} | |
func ~=<T, U>(lhs: T, rhs: (U) -> T) -> Bool { | |
var lhs = lhs | |
var result = rhs(body(of: &lhs)) | |
return flag(of: &lhs) == flag(of: &result) | |
} | |
enum Enum { | |
case foo(Int) | |
case bar(String) | |
case qux(Int) | |
} | |
let items: [Enum] = [.foo(1), .bar("hi"), .foo(2)] | |
let filtered = items.filter { $0 ~= Enum.bar } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I was excited for this solution, but it crashes in a couple of scenarios :( First, extend the enum out to have a non-associated type, and an associative type with a more complex tuple. Extend the test items list to include instances of these.
The following breaks because of expected argument types, but could be overcome with an alternate definition for ~=:
Testing for .bar crashes:
Though interestingly, testing for .foo still works, I think because the first parameter is still an Int type (if you reverse xyzzy to be (String, Int), then it's .bar that works and .foo that crashes):