简体   繁体   English

在DDMathParser(Swift)中定义自定义函数

[英]Define custom functions in DDMathParser (Swift)

I am attempting to define and format a custom function in Swift via the mechanisms built into DDMathParser. 我正在尝试通过DDMathParser内置的机制在Swift中定义和格式化自定义函数。 I have tried following the instructions on the Wiki, but for someone who is relatively new to Swift coding there are not enough specifics. 我尝试按照Wiki上的说明进行操作,但对于Swift编码相对较新的人来说,没有足够的细节。 The function I want to create would be called "dsi" and would call the already built-in functions sin() and dtor() like so: sin(dtor()). 我要创建的函数将被称为“ dsi”,并会像这样调用已内置函数sin()和dtor():sin(dtor())。

Any advice? 有什么建议吗?

Thanks! 谢谢!

An example of declaring a custom function can be found in the unit tests for DDMathParser , which I'll include here: 可以在DDMathParser的单元测试中找到一个声明自定义函数的示例 ,我将在其中包括:

func testCustomFunction() {
    let function = Function(name: "foo", evaluator: { (args, subs, eval) throws -> Double in
        return 42
    })

    let eval = Evaluator()
    guard XCTAssertNoThrows(try eval.registerFunction(function)) else { return }
    guard let e = XCTAssertNoThrows(try Expression(string: "foo()")) else { return }
    guard let d = XCTAssertNoThrows(try eval.evaluate(e)) else { return }
    XCTAssertEqual(d, 42)
}

You would obviously want to provide a different implementation of the evaluation block passed to the Function constructor. 您显然希望提供传递给Function构造Function的评估块的不同实现。

Incidentally, are you aware that DDMathParser has support for the exact case you're describing already? 顺便说一句,您是否知道DDMathParser支持您已经描述的确切情况? The Evaluator object has an angleMeasurementMode property. Evaluator对象具有angleMeasurementMode属性。 The default value is .Radians , but you can change it to .Degrees if you create your own evaluator . 默认值为.Radians但您可以将其更改为.Degrees如果您创建自己的评估程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM