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)
正如在评论中已经说过的那样,你必须调用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)
归档时间: |
|
查看次数: |
4426 次 |
最近记录: |