I have a custom structure with several fields, and I would like to map the template to it in the swift switch , so I can configure the comparison by comparing one of the fields with a regular expression.
eg. Given this structure:
struct MyStruct { let header: String let text: String }
I would like to map the pattern as follows:
switch(someInstance) { case ("h1", "[az]+"): ... case ("h1", "0-9+"): ... }
I tried to get this to work using the pattern matching function as follows:
func ~=(pattern: (String, String), value: MyStruct) -> Bool { return value.header == pattern.0 && value.text.range(of: pattern.1, options: .regularExpression) != nil }
But then Xcode (9) does not compile with this error:
Sample template cannot match values ββof non-tuple type "MyStruct"
The best I have been able to achieve is the following:
struct MatchMyStruct { let header: String let regex: String init(_ header: NSString, _ regex: String) { self.header = header self.regex = regex } } func ~=(pattern: MatchMyStruct, value: MyStruct) -> Bool { return value.header == pattern.header && value.text.range(of: pattern.regex, options: .regularExpression) != nil }
This allows me to map the pattern as follows:
switch(someInstance) { case MatchMyStruct("h1", "[az]+"): ... case MatchMyStruct("h1", "0-9+"): ... }
While this is functional, I would prefer not to have the so-called MatchMyStruct wrappers.
Swift seems to have a magical secret sauce to match patterns with tuples that get in the way. Can I do anything here?