在变量中分配运算符函数

Gil*_*jor 4 swift

我正在尝试为**(未存在的)运算符创建一个通用函数,该运算符将计算左数字到正确数字的幂.

它适用于0和正数,但我想要处理负数.

我想到了几个想法,但我想尝试将现有运算符的功能存储在变量中,如下所示:

var operation = *
Run Code Online (Sandbox Code Playgroud)

要么

var operation = /
Run Code Online (Sandbox Code Playgroud)

使用operation(a, b)会像a*b或那样做a/b

在Swift中这样的事情可能吗?

rin*_*aro 20

你不能做这个:

var operation = *
Run Code Online (Sandbox Code Playgroud)

但是,你CAN这样做:

var operation:(Int, Int) -> Int = (*)

operation(4,2) // -> 8
Run Code Online (Sandbox Code Playgroud)

因为*有很多重载类型:

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
Run Code Online (Sandbox Code Playgroud)

我们必须明确指定哪一个.