Swift中的NSExpression计算器

Ché*_*éyo 6 cocoa-touch ios swift ios8

我试图复制需要在Swift 中的Objective-C编写计算器但我的代码不起作用.

import Foundation

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

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

println(result)
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 9

正如在评论中已经说过的那样,你必须调用expressionValueWithObject() 表达式:

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

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")
}
Run Code Online (Sandbox Code Playgroud)