Created
February 9, 2017 14:53
-
-
Save delight-by/551a60144c257cee6ab3492585d04a75 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
| // 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