swiftnsexpression

Evaluating a string in swift


I am trying to make a simple a calculator app in Swift + Xcode. I realised that there was a strange issue with the solver: I had used the function shown in this question which works for most problems but when you involve decimal places: e.g. "3/2" you would expect it to return "1.5". It will return "1.0".

Here is the function I am using:

func mathsSolver(item: String) -> String {
    let result = NSExpression(format: item).expressionValue(with: nil, context: nil) as! Double
    return "\(result)"
}

You can call this function with:

print(mathsSolver(item: "3/2")) //this will print 1.0

Any ideas?


Solution

  • You have to pass the double value so that you can get result 1.5

    print(mathsSolver(item: "3.0/2.0"))

    Above you are trying to pass Int value so that it is not giving you the proper result because integer division will always gives you the answer in integer.