Created
January 31, 2017 18:40
-
-
Save erica/4e8176db0cf1937fe60ce7849aed1e87 to your computer and use it in GitHub Desktop.
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
enum Enum { | |
case foo(Int) | |
case bar(String) | |
case snog(Int) | |
} | |
let items: [Enum] = [.foo(1), .bar("hi"), .foo(2)] | |
let filtered = items.filter({ switch $0 { case .foo: return true; default: return false } }) | |
let filtered2 = items.filter({ for case .foo in [$0] { return true }; return false }) | |
extension Enum { | |
var isFoo: Bool { | |
switch self { case .foo: return true; default: return false } | |
} | |
} | |
let filtered3 = items.filter({ $0.isFoo }) | |
extension Enum { | |
static func ~= (lhs: Enum, rhs: Enum) -> Bool { | |
let lhsCase = Array(Mirror(reflecting: lhs).children) | |
let rhsCase = Array(Mirror(reflecting: rhs).children) | |
return lhsCase[0].0 == rhsCase[0].0 | |
} | |
} | |
let filtered4 = items.filter({ $0 ~= .foo(0) }) | |
print(filtered4) | |
import Foundation | |
extension Enum { | |
var caseName: String { | |
return "\(Array(Mirror(reflecting: self).children)[0].0!)" | |
} | |
static func ~= <T>(lhs: Enum, rhs: (T) -> Enum) -> Bool { | |
let lhsCase = lhs.caseName | |
let prefixString = "Mirror for (\(T.self)) -> " | |
let typeOffset = prefixString.characters.count | |
let typeString = "\(Mirror(reflecting: rhs).description)" | |
let rhsCase = typeString.substring(from: typeString.index(typeString.startIndex, offsetBy: typeOffset)) | |
return true | |
} | |
} | |
let x = Enum.foo(_) | |
let rr = Mirror(reflecting: x).description | |
// print(Array(rr.children)) | |
items[0] ~= x |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment