title: Idiomatic way to model opcodes with embedded data in Swift
body: <p>Swift enums seem like a great fit for modeling byte opcodes in Swift3. For example:</p>
  
  <pre><code>enum MathOpCode:UInt8 {
      case Add = 0
      case Subtract = 1
      case Multiply = 2
      case Divide = 3
  }
  
  let a = 42
  let b = 13
  let someByte = 2
  
  if let opcode = OpCode(rawValue: someByte) {
      switch opcode {
      case .Add:
          return a + b
      case .Subtract:
          return a - b
      case .Multiply:
          return a * b
      case .Divide:
          return a / b
      }
  }
  </code></pre>
  
  <p>This can be really expressive for writing binary protocols. The enum nicely captures the logical opcodes, and the switches read nicely then. Where it's breaking down for me, is where OpCodes include small amounts of data. IOW, let's say I add an OpCode called <code>AddSmallConstant</code> which is meant to represent all opcodes matching <code>0b01nnnnnn</code> where the top two bits must be <code>01</code>, but the bottom 6 bits are an embedded constant ranging 0-63. I could add 64 cases to my enum...</p>
  
  <pre><code>enum MathOpCode:UInt8 {
      ...
      case AddConstant0 = 0b01000000
      case AddConstant1 = 0b01000001
      ...
      case AddConstant63 = 0b01111111
  }
  </code></pre>
  
  <p>This doesn't really scale well. And to get the embedded value, I have to use rawValue and masking operations to get it anyway. And I can't have a switch statement that looks like</p>
  
  <pre><code>case MathOpCode.AddConstant0...MathOpCode.AddConstant63
  </code></pre>
  
  <p>to match the whole range, because enum cases can't be turned into ranges. The alternate is to use <code>rawValue</code> all over the place:</p>
  
  <pre><code>switch opCode.rawValue {
  case MathOpCode.Add.rawValue:
      ...
  case MathOpCode.Subtract.rawValue:
      ...
  case (MathOpCode.AddConstant0.rawValue)...(MathOpCode.AddConstant63.rawValue):
      ...
  }
  </code></pre>
  
  <p>Now the enum just seems like baggage, better to just define a bunch of constant let's up top of my my file. Am I missing a better pattern I can use in Swift to express these types of relationships and patterns?</p>