Mathematical sign as a function parameter

Is there any way to send a mathematical sign (+, -, *) as function parameters? I want to call a function reduce()for different characters.

+4
source share
4 answers

In fast signs, there is a function name for a given mathematical operation. To pass a character as a parameter, the type of the parameter must be a function that takes two numbers and returns a number. If you click on any character, you will see its definition as follows:

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

:

func reduce(sign: (Int,Int)->Int) -> Int{

    return sign(2,3)
}

reduce(*)
reduce(-)
+7
func doSomeCalculation(_ fun:((Int, Int) -> Int)) -> Int {
    return fun(12,13)
}

doSomeCalculation(+) // 25
doSomeCalculation(-) // -1

UInt, IntXX ..

+ , . func , , .

+ reduce.

+5

, reduce(), , , , , .

Think of operators as functions / closures, and you'll see why this is possible in Swift. Actually, operators are similar to functions - they are called closures.

Also think about how you can add new operators - you define a function with the name of the operator, which takes a number of parameters equal to the value of the operator.

Thus, the following is syntactically correct and provides the expected result ( 6):

[1,2,3].reduce(0, combine: +)
+4
source

Send as character, then switch to identification:

func acceptASign(sign: Character) {
    switch sign {
    case "+":
        //do some addition
    case "-":
        //do some subtraction
    case "*":
        //do some multiplication
    case "/":
        //do some division
    default:
        break;
    }
}
-2
source

Source: https://habr.com/ru/post/1621978/


All Articles