简体   繁体   中英

Define custom functions in DDMathParser (Swift)

I am attempting to define and format a custom function in Swift via the mechanisms built into DDMathParser. I have tried following the instructions on the Wiki, but for someone who is relatively new to Swift coding there are not enough specifics. 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()).

Any advice?

Thanks!

An example of declaring a custom function can be found in the unit tests for DDMathParser , which I'll include here:

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.

Incidentally, are you aware that DDMathParser has support for the exact case you're describing already? The Evaluator object has an angleMeasurementMode property. The default value is .Radians , but you can change it to .Degrees if you create your own evaluator .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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