Reputation: 2259
Can I somehow send the mathematical sign (+, -, *) as function parameters? I want to call reduce()
function for different sign.
Upvotes: 16
Views: 4105
Reputation: 57184
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
.
Upvotes: 8
Reputation: 32870
Yes, you can send any binary operator to the reduce()
function, providing the original value and the elements in the collection are of the same type, and thus the operator can be applied.
Think at operators as functions/closures and you'll understand why this is possible in Swift. In fact operators are just like functions - they are named closures.
Also think at the way new operators can be added - you define a function with the operator name that takes a number of parameters equal to the operator arity.
Thus, the following is syntactically correct, and provides the expected output (6
):
[1,2,3].reduce(0, combine: +)
Upvotes: 5
Reputation: 10296
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(-)
Upvotes: 23
Reputation: 2098
Send as a Character, then switch to identify:
func acceptASign(sign: Character) {
switch sign {
case "+":
//do some addition
case "-":
//do some subtraction
case "*":
//do some multiplication
case "/":
//do some division
default:
break;
}
}
Upvotes: -3