I'm trying to create a generic function for the **
(unexisting) operator that would compute the left number to the power of the right number.
It works for 0 and and positive numbers, but i would like tackling negative numbers.
Several ideas come to mind, but I would like to try out storing the function of existing operators in a variable like so:
var operation = *
or
var operation = /
using operation(a, b)
would do the same as a*b
or a/b
Is such a thing possible in Swift?
You cannot do this:
var operation = *
But, you CAN do this:
var operation:(Int, Int) -> Int = (*)
operation(4,2) // -> 8
Because *
has many overloaded types:
func *(lhs: UInt32, rhs: UInt32) -> UInt32
func *(lhs: Int32, rhs: Int32) -> Int32
func *(lhs: UInt64, rhs: UInt64) -> UInt64
func *(lhs: Int64, rhs: Int64) -> Int64
func *(lhs: UInt, rhs: UInt) -> UInt
func *(lhs: Int, rhs: Int) -> Int
func *(lhs: Float, rhs: Float) -> Float
func *(lhs: Double, rhs: Double) -> Double
func *(lhs: Float80, rhs: Float80) -> Float80
we have to explicitly specify which one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With