Dave DeLong edited this page Sep 18, 2015 · 4 revisions

There are two of ways to evaluate strings, depending on how much customization you want to do.

All parsing and evaluation operations have the ability to produce errors, so you must use Swift's error handling mechanism.


let value = try "1 + 2".evaluate()

The evaluate() method on String is intended for the most basic use-cases. While it does not "swallow" any errors, it offers very little in the way of customization. If your string contains variables, you can optionally pass in a substitutions dictionary:

let value = try "$foo + 2".evaluate(["foo": 40])


The other approach is using the Evaluator object, which requires an Expression:

let expression = try Expression(string: "1 + 2")

let evaluator: Evaluator = ...
let value = try evaluator.evaluate(expression)

When evaluating with an Evaluator, you have access to most of the high-level customizability options of DDMathParser. For example, prior to evaluation you may change the default angle measurement mode:

evaluator.angleMeasurementMode = .Degrees

Using an Evaluator also allows you to define your own functions, override existing functions, or dynamically resolve variable values.

To access the full range of customizability, including customizing the behavior of the % operator, defining your own operators, or adding new tokens for existing operators, you'll customize the creation of the Expression object itself. For more information, see the Advanced Usage page.