0

我使用 DDMathParser 使用 Swift 求解公式表达式。以下代码可以正常工作,但是,隐式乘法不能。阅读它应该工作的文档......那么,我在这里想念什么?我的代码:

...
substitutions.updateValue(3, forKey: "x")
let myString = "3$x"

    do{
        let expression = try Expression(string: myString, operatorSet: operatorSet, options: myTRO, locale: myLocale)
        let result = try evaluator.evaluate(expression, substitutions: substitutions)
        print("expression is: \(expression), the result is : \(result)")
    } catch {
        print("Error")
    }
...

代码抛出“错误”。使用字符串"3*$x"按预期计算表达式。

4

2 回答 2

1

DDMathParser 作者在这里。

因此,.invalidFormat当框架有一系列标记并且正在寻找一个操作符以弄清楚它周围发生了什么时,就会引发错误。如果它找不到运算符但仍有要解析的令牌但没有运算符,则抛出.invalidFormat错误。

这意味着您有一个3.0数字标记和一个$x变量标记,但没有×乘法标记。

我还看到您正在传递一组自定义TokenResolverOptionsmyTRO变量)。我猜你正在传递一个包含该.allowImplicitMultiplication值的选项集。如果我尝试在3$x 没有.allowImplicitMultiplication解析器选项的情况下进行解析,则会.invalidFormat引发错误。

于 2018-04-16T08:43:16.783 回答
0

Ok, got it myself. As Dave DeLong mentioned .allowImplicitMultiplication is included by default in the options but will get ignored when creating custom options. Since I want to use localized expressions (decimal separator within expression string is local) I need to use the advanced definition of Expression:

let expression = try Expression(string: ..., operatorSet: ..., options: ..., locale: ...)

In order to use the localized string option I defined let myLocale = NSLocale.current but accidentally also created a new operatorSet new options and passed it to the expression definition. The right way is not to create custom operatorSet and options but to use the defaults within the Expression definition:

let expression = try Expression(string: expressionString, operatorSet: OperatorSet.default, options: TokenResolverOptions.default, locale: myLocale)

Dave DeLong did a really great job in creating the DDMatParser framework. For newbies it is very hard to get started with. The wiki section at DDMathParser is pretty basic and doesn't give some details or examples for all the other great functionality DDMatParser is providing.

于 2018-04-21T11:31:16.230 回答