0

Below is the answer to the original question of how to add a power operator for Int numbers:

infix operator ^^ { associativity left precedence 160 }
func ^^ (radix: Int, power: Int) -> Int {
    return Int(pow(CGFloat(radix), CGFloat(power)))
}

How would one generalise this so that it works for Double, Float, and Int?

Community
  • 1
  • 1
fiship
  • 15
  • 2

1 Answers1

0

You cannot "generalize" it. You have to implement it for each type separately.

If you look in the Swift header, you will see that that is exactly what Swift itself does for the built-in operators such as +. There is no "general" + function; there is one + function for every numeric type.

Thus:

infix operator ^^ { associativity left precedence 160 }
func ^^ (radix: Int, power: Int) -> Int {
    return Int(pow(CGFloat(radix), CGFloat(power)))
}
func ^^ (radix: Double, power: Double) -> Double {
    return Double(pow(CGFloat(radix), CGFloat(power)))
}
// ... and so on for as many types as you like ...
matt
  • 515,959
  • 87
  • 875
  • 1,141