swift

Generic extension on Numeric protocol


I am trying to extend Swift's Numeric protocol with a method that divides one Numeric type by another of the same type like this:

extension Numeric {
  func percentage<T>(of: T) -> T where T.Type == Self.Type {
    return self / of
  }
}

But I get the error

Same-type requirement makes generic parameters 'T' and 'Self' equivalent

It works when it's not a protocol extension, but I'd love to know if it's possible to do it as an extension and what this error means.

This works:

func percentage<T: Numeric>(n1: T, n2: T) -> T {
  return n1 / n2
}
let d = x(n1: 2.0, n2: 3.0)

Solution

  • There's no need for T.

    extension Numeric {
        func percentage<Self>(of whole: Self) -> Self {
            return self / whole
        }
    }