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.