Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add custom pattern matching to make your switch statements magical
struct CustomMatcher<Value> {
let closure: (Value) -> Bool
static func ~= (caseValue: CustomMatcher<Value>, switchValue: Value) -> Bool {
caseValue.closure(switchValue)
}
static func ~= (caseValue: Value, switchValue: CustomMatcher<Value>) -> Bool {
switchValue.closure(caseValue)
}
}
extension CustomMatcher where Value == String {
static func hasPrefix(_ prefix: String) -> CustomMatcher {
CustomMatcher { $0.hasPrefix(prefix) }
}
}
extension CustomMatcher where Value: Collection {
static var isEmpty: CustomMatcher {
CustomMatcher { $0.isEmpty }
}
}
// random just so that playground doesn't find it deterministic at compile time
let string = "Hello-\(Int.random(in: 0..<10))"
// Apply different custom operators/matchers on different cases:
switch string {
case .isEmpty: print("Nothing to say?")
case "a": print("Is 'a'")
case "b": print("Is 'b'")
case .hasPrefix("Hello"): print("Hello to you too!")
default: print("Huh?")
}
// "Hello to you too!"
// If you happen to want to apply the same operator on all the cases, you can apply it on the switch instead:
switch CustomMatcher.hasPrefix(string) {
case "a": print("Starts with 'a'")
case "b": print("Starts with 'b'")
case "Hello": print("Hello to you too!")
default: print("Huh?")
}
// "Hello to you too!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment