Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSExpression Calculator in Swift

I am trying to duplicate Need to write calculator in Objective-C in Swift but my code is not working.

import Foundation

var equation:NSString = "5*(2.56-1.79)-4.1"

var result = NSExpression(format: equation, argumentArray: nil)

println(result)
like image 980
Chéyo Avatar asked Jul 11 '14 18:07

Chéyo


1 Answers

As already said in a comment, you have to call expressionValueWithObject() on the expression:

let expr = NSExpression(format: equation)
if let result = expr.expressionValueWithObject(nil, context: nil) as? NSNumber {
    let x = result.doubleValue
    println(x)
} else {
    println("failed")
}

Update for Swift 3:

let expr = NSExpression(format: equation)
if let result = expr.expressionValue(with: nil, context: nil) as? Double {
    print(result) // -0.25
} else {
    print("failed")
}
like image 124
Martin R Avatar answered Sep 21 '22 14:09

Martin R