Last active
January 5, 2020 21:40
-
-
Save AliSoftware/8cd7f15af79a0d1122941462056079c4 to your computer and use it in GitHub Desktop.
Add custom pattern matching to make your switch statements magical
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
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