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?