title: Swift generic number types and math
body: <p>I'm trying to wrap my head around the ins and outs of Swift generics and make some common math functions. I'm trying to implement a <code>mod</code> function, but not quite sure the best way to get it working using generics.</p>
  
  <p>Here's what my <code>mod</code> function looks like:</p>
  
  <pre><code>func mod&lt;N: NumericType, I: IntegerType&gt;(_ x: N, _ y: I) -&gt; N {
      return x - y * floor(x/y)
  }
  </code></pre>
  
  <p>But I'm getting this error: </p>
  
  <pre><code>error: binary operator '/' cannot be applied to operands of type 'N' and 'I'
      return x - y * floor(x/y)
  </code></pre>
  
  <p>And here's my <code>NumericType</code> declaration for decimal and integer type numbers:</p>
  
  <pre><code>protocol NumericType: Comparable {
      static func +(lhs: Self, rhs: Self) -&gt; Self
      static func -(lhs: Self, rhs: Self) -&gt; Self
      static func *(lhs: Self, rhs: Self) -&gt; Self
      static func /(lhs: Self, rhs: Self) -&gt; Self
      static func %(lhs: Self, rhs: Self) -&gt; Self
  }
  
  protocol DecimalType: NumericType {
      init(_ v: Double)
  }
  
  protocol IntegerType: NumericType {
      init(_ v: Int)
  }
  
  extension CGFloat : DecimalType { }
  extension Double  : DecimalType { }
  extension Float   : DecimalType { }
  
  extension Int     : IntegerType { }
  extension Int8    : IntegerType { }
  extension Int16   : IntegerType { }
  extension Int32   : IntegerType { }
  extension Int64   : IntegerType { }
  extension UInt    : IntegerType { }
  extension UInt8   : IntegerType { }
  extension UInt16  : IntegerType { }
  extension UInt32  : IntegerType { }
  extension UInt64  : IntegerType { }
  </code></pre>