NSExpression Calculator in Swift

cocoa-touch, ios, ios8, swift

Solution

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")
}

Problem

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) ```

Original source