1

The below Swift code is giving 10 as an answer but I expect to have 12.5.

var numericExpression = "5 * (5 / 2)"

let expression = NSExpression(format: numericExpression)
var result = expression.expressionValue(with: nil, context: nil)

The reason is simply the integer division. The program logic is not letting me to give something like "5 * (5.0 / 2)". Therefore I came up with an idea to use custom Swift operator something like ^/^ to represent the floting point devotion.

infix operator ^/^: MultiplicationPrecedence

extension Int {

    static func ^/^ (left: Int, right: Int) -> Double {

        return Double(left) / Double(right)
    }
}

extension Double {

    static func ^/^ (left: Double, right: Double) -> Double {

        return left / right
    }
}

extension NSNumber {

    static func ^/^ (left: NSNumber, right: NSNumber) -> NSNumber {

        return NSNumber(value: left.floatValue / right.floatValue)
    }
}

with the replacement like this

let expression = NSExpression(format: "5 * (5 ^/^ 2)")
var result = expression.expressionValue(with: nil, context: nil)

but the result is

"libc++abi.dylib: terminating with uncaught exception of type NSException"

How can I make it possible? Any ideas?

JJJ
  • 32,902
  • 20
  • 89
  • 102
Goppinath
  • 10,569
  • 4
  • 22
  • 45
  • 1
    NSExpression is quite limited and *cannot* be customized. Here https://stackoverflow.com/q/46550658/1187415 are some "hacks" to force floating point division, but I can only recommend to use a 3rd party expression parser/evaluator such as https://github.com/davedelong/DDMathParser/wiki – Martin R Nov 13 '17 at 10:59
  • @Willeke, please read the question carefully before you give some random answer. – Goppinath Nov 13 '17 at 13:27

0 Answers0