我正在尝试复制 Need to write calculator in Objective-C在 Swift 中,但我的代码无法正常工作。
import Foundation
var equation:NSString = "5*(2.56-1.79)-4.1"
var result = NSExpression(format: equation, argumentArray: nil)
println(result)
最佳答案
如评论中所述,您必须调用 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")
}
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")
}
关于ios - Swift 中的 NSExpression 计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24704028/