Skip to content

Instantly share code, notes, and snippets.

@delight-by
Created February 9, 2017 14:53
Show Gist options
  • Select an option

  • Save delight-by/551a60144c257cee6ab3492585d04a75 to your computer and use it in GitHub Desktop.

Select an option

Save delight-by/551a60144c257cee6ab3492585d04a75 to your computer and use it in GitHub Desktop.
// a fancy syntax to filter enums
enum Enum: EquatableEnum {
case foo(Int)
case bar(String)
case qux(Int, String)
}
protocol EquatableEnum { }
extension EquatableEnum {
static func ~= <A> (lhs: Self, builder: @escaping (A) -> Self) -> Bool {
guard let lhsDecomposition = Mirror(reflecting: lhs).children.first,
let lhsValue = lhsDecomposition.value as? A,
let rhsDecomposition = Mirror(reflecting: builder(lhsValue)).children.first,
lhsDecomposition.label == rhsDecomposition.label
else { return false }
return true
}
}
let items: [Enum] = [.foo(1), .bar("hi"), .qux(1, "hi"), .foo(2), .qux(2, "bye")]
let foos = items.filter { $0 ~= Enum.foo }
let quxs = items.filter { $0 ~= Enum.qux }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment