今天「畅想资源」就来向大家推荐一款功能强大的数学表达式解析器「DDMathParser」,这一函式库可以直接将类似 5^(2/(1+2)) 类的数学表达式计算出结果,这一开源函式库的使用可比自带的 formula.expression.expressionValueWithObject 方便多了 
安装
将以下内容加入你的「Podfile」中即可:(Swift的话同样也不要忘记 use_frameworks! 这一重要的一行)
| 1 | pod 'DDMathParser', '~> 2.0' | 
使用
首先要记得先 import 这一函式库:(注意是「MathParser」)
| 1 | import MathParser | 
然后试试看算最简单的一条算式:(记得使用 do { } catch { } 以进行错误处理)
| 1 2 3 4 5 6 7 | do {     let value = try "1 + 2".evaluate()     print("Result: \(value)")     // "Result: 3.0" } catch let error as NSError {     print("Error: \(error.localizedDescription)") } | 
如果想要用类似 M 等的变量呢?很简单:
| 1 2 3 4 5 6 7 | do {     let value = try "$M + 2".evaluate(["M": 40])     print("Result: \(value)")     // "Result: 42.0" } catch let error as NSError {     print("Error: \(error.localizedDescription)") } | 
而如果你想要计算三角函数的话,则需要自己稍微定义一下是度度量(degree)还是弧度量(radian):
| 1 2 3 4 5 6 7 8 9 10 11 12 | do {     var evaluator = Evaluator()     evaluator.angleMeasurementMode = .Degrees       // Or ".Radians"     let expression = try Expression(string: "sin(5)")     let value = try evaluator.evaluate(expression)     print("Result: \(value)")     // "Result: 0.0871557427476582" } catch let error as NSError {     print("Error: \(error.localizedDescription)") } | 
另外如果你的输入是由用户进行的话,一定一定一定要记得妥善处理错误:
| 1 2 3 4 5 6 7 | do {     let value = try "1nd.2/23".evaluate()     print("Result: \(value)") } catch let error as NSError {     print("Error: \(error.localizedDescription)")     // "Error: The operation couldn’t be completed. (MathParser.EvaluationError error 0.)" } | 
| 1 2 3 4 5 6 7 | do {     let value = try "1/0".evaluate()     print("Result: \(value)") } catch let error as NSError {     print("Error: \(error.localizedDescription)")     // "Error: The operation couldn’t be completed. (MathParser.EvaluationError error 2.)" } | 
大家也可以前往该项目的Github主页及Wiki查看更多使用方法:  
 
历史上的今天
2013年:神人论坛回复(4条评论)
