Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning operator function in variable

Tags:

swift

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?

like image 886
Gilles Major Avatar asked Nov 09 '14 14:11

Gilles Major


1 Answers

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.

like image 58
rintaro Avatar answered Oct 04 '22 21:10

rintaro