我能否以某种方式发送数学符号(+、-、*)作为函数参数?我想为不同的符号调用 reduce()
函数。
最佳答案
在 swift 中,符号是指定数学运算的函数名称。要将符号作为参数传递,参数类型必须是接受两个数字并返回一个数字的函数。如果您命令 + 单击任何标志,您将看到其定义如下:
public func +(lhs: UInt8, rhs: UInt8) -> UInt8
public func +(lhs: Int8, rhs: Int8) -> Int8
public func +(lhs: UInt16, rhs: UInt16) -> UInt16
public func +(lhs: Int16, rhs: Int16) -> Int16
public func +(lhs: UInt32, rhs: UInt32) -> UInt32
public func +(lhs: Int32, rhs: Int32) -> Int32
public func +(lhs: UInt64, rhs: UInt64) -> UInt64
public func +(lhs: Int64, rhs: Int64) -> Int64
public func +(lhs: UInt, rhs: UInt) -> UInt
public func +(lhs: Int, rhs: Int) -> Int
在您的情况下,您的 reduce 函数应如下所示
func reduce(sign: (Int,Int)->Int) -> Int{
return sign(2,3)
}
reduce(*)
reduce(-)
关于swift - 数学符号作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34496148/