title: Defining a Swift Protocol for Arbitrary, Int-based Enums
body: <p>I have this enumeration representing a color, and I have added several methods to conveniently obtain new instances based on arithmetic operations on the original's raw value:</p>
  
  <pre><code>enum Color : Int
  {
      case Red = 0
      case Green
      case Blue
  
      case Cyan
      case Magenta
      case Yellow
  
  
      static func random() -&gt; Color
      {
          return Color(rawValue: Int(arc4random_uniform(6)))!
      }
  
      func shifted(by offset:Int) -&gt; Color
      {
          return Color(rawValue: (self.rawValue + offset) % 6)!
          // Cyclic: wraps around
      }
  }
  </code></pre>
  
  <p>(This harks back to the old enums being just int constants)</p>
  
  <p>The problem is, I have several other int-based enums where I would like to introduce similar functionality, but without duplicating code. </p>
  
  <p>I think I should define a protocol extension on <code>RawRepresentable</code> where <code>RawValue == Int</code>:</p>
  
  <pre><code>extension RawRepresentable where RawValue == Int
  {
  </code></pre>
  
  <p>...but that's where my understanding of the syntax ends. </p>
  
  <p>Ideally, I would like to require a static method returning the number of cases, and a provide default implementation of both <code>random()</code> and <code>shifted(_:)</code> above that takes that into account (instead of the hard-coded 6 here).</p>
  
  <p><strong>CONCLUSION:</strong> I have accepted <a href="https://stackoverflow.com/a/33579080/433373">the answer by Zoff Dino</a>. Even though <a href="https://stackoverflow.com/a/33579304/433373">the answer given by Rob Napier</a> is exactly what I asked for, it turns out what I was asking for was not the most elegant design after all, and the other answer suggests a better approach. Still, I have upvoted both answers; thanks everyone.</p>