Mathematical sign as function parameter
func doSomeCalculation(_ fun:((Int, Int) -> Int)) -> Int {
return fun(12,13)
}
doSomeCalculation(+) // 25
doSomeCalculation(-) // -1
The same can be done for UInt
, the IntXX
, etc.
+
is basically simply a function that takes two arguments and returns the sum of it. Since func
tions are objects like any other you can pass them around as such.
The same way you can pass +
into reduce
.
In swift signs are functions name for a specified mathematic operation. To pass sign as parameter the parameter type must be function that takes two numbers and return a number. If you command + click on any sign you will see its definition as follow :
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
In your case your reduce function should look as the following one
func reduce(sign: (Int,Int)->Int) -> Int{
return sign(2,3)
}
reduce(*)
reduce(-)