Anton Ödman Anton Ödman - 2 months ago 17
Swift Question

Operator in arguments (Swift)

I am all new to swift programming and I have tried to make a function which is solving a simple math calculation based on the three arguments, which is the operator type, and two numbers that should be calculated. After a time now I have made it work to an extent that I am satisfied with, in which the code looks like this:

func calculation(operatorType: String, number1: Double, number2: Double) -> Double {

if operatorType == "+" {
return number1 + number2

} else if operatorType == "-" {
return number1 - number2

} else if operatorType == "/" {
return number1 / number2

} else if operatorType == "*" {
return number1 * number2

} else {
return 0
}
}


As I said, it works fairly well. I have to put in the operatorType with quotation marks as it is a String type, I have tried to get rid of them without any success.

But now to the point:

I tried making the code a bit simpler, I was thinking: it is possible to insert the whole "use the same operator as the argument" in one code? I tried like:

if operatorType == "*" || operatorType == "-"....
return number1 + operatorType + number2


To make it an correct equation, but without any success. So my question is really, I am thinking correct, it is possible to do so, and in that case, how? Even though it is really basic code it would be good to maybe use a more efficient way with less code, that also actually works better.

Thank you!

EDIT:
Changed the name to one that is not so vague.

Answer

Swift does not yet have the Reflection system necessary to fetch arbitrary functions (such as those operator functions you're using) by a String name.

You can improve your code by using a switch statement:

func performOperation1(operatorName: String, _ operand1: Double, _ operand2: Double) -> Double {
    switch (operatorName) {
    case "+": return operand1 + operand2
    case "-": return operand1 - operand2
    case "*": return operand1 * operand2
    case "/": return operand1 / operand2
    default: fatalError("Unsupported Operator Name")
    }
}

To avoid repeating operand1 and operand2, you can store the operator function into a closure variable, and call it once at the end:

func performOperation(operatorName: String, _ operand1: Double, _ operand2: Double) -> Double {
    var f: (Double, Double) -> Double

    switch (operatorName) {
    case "+": f = (+)
    case "-": f = (-)
    case "*": f = (*)
    case "/": f = (/)
    default: fatalError("Unsupported Operator Name")
    }

    return f(operand1, operand2)
}
Comments