title: swift 4: pattern match an object against a tuple (Tuple pattern cannot match values of the non-tuple type)
body: <p>I have a custom struct with a few fields, and I'd like to pattern match against it in a swift <code>switch</code> statement so I can customise the matching, by comparing one of the fields against a regex.</p>
  
  <p>E.g. Given this structure:</p>
  
  <pre><code>struct MyStruct {
      let header: String
      let text: String
  }
  </code></pre>
  
  <p>I'd <em>like</em> to pattern match like this:</p>
  
  <pre><code>switch(someInstance) {
      case ("h1", "[a-z]+"): ...
      case ("h1", "0-9+"): ...
  }
  </code></pre>
  
  <p>I tried to get this to work using a pattern matching function as follows:</p>
  
  <pre><code>func ~=(pattern: (String, String), value: MyStruct) -&gt; Bool {
      return value.header == pattern.0 &amp;&amp; value.text.range(of: pattern.1, options: .regularExpression) != nil
  }
  </code></pre>
  
  <p>But then Xcode (9) fails to compile with this error:</p>
  
  <p><strong>Tuple pattern cannot match values of the non-tuple type 'MyStruct'</strong></p>
  
  <p>The best I've been able to achieve is the following:</p>
  
  <pre><code>struct MatchMyStruct {
      let header: String
      let regex: String
  
      init(_ header: NSString, _ regex: String) {
          self.header = header
          self.regex = regex
      }
  }
  
  func ~=(pattern: MatchMyStruct, value: MyStruct) -&gt; Bool {
      return value.header == pattern.header &amp;&amp; value.text.range(of: pattern.regex, options: .regularExpression) != nil
  }
  </code></pre>
  
  <p>This lets me pattern match like this:</p>
  
  <pre><code>switch(someInstance) {
      case MatchMyStruct("h1", "[a-z]+"): ...
      case MatchMyStruct("h1", "0-9+"): ...
  }
  </code></pre>
  
  <p>While this is functional, I'd much prefer not to have to have the <code>MatchMyStruct</code> wrappers explicit like that.</p>
  
  <p>It seems like swift has some magic secret sauce for pattern matching with tuples that's getting in the way. Is there anything I can do here?</p>