Swift中的NSExpression计算器 [英] NSExpression Calculator in Swift

查看:82
本文介绍了Swift中的NSExpression计算器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试复制需要在Objective-C中编写计算器在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)


推荐答案

正如评论中所述,您必须致电 expressionValueWithObject()
在表达式上:

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






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

这篇关于Swift中的NSExpression计算器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆