Source

Eval is a lightweight interpreter framework written in Swift, for iOS, macOS, and Linux platforms. It evaluates expressions at runtime, with operators and data types you define.

The framework currently supports two different types of execution modes:

Strongly typed expressions: like a programming language
Template languages: evaluating expressions in arbitrary string environments
Let's see just a few examples:

It's extremely easy to formulate expressions (and evaluate them at runtime), like

And templates, such as

And so on... The result of these expressions depends on the content, determined by the evaluation. It can be any type which is returned by the functions (String, [Double], Date, or even custom types of your own.)

Getting started

For the expressions to work, you'll need to create an interpreter instance, providing your data types and expressions you aim to support, and maybe some input variables - if you need any.

    let interpreter = TypedInterpreter(dataTypes: [number, string, boolean, array, date],
                                       functions: [multipication, addition, ternary],
                                       context: Context(variables: ["x": 2.0]))

And call it with a string expression, as follows.

    let result = interpreter.evaluate("2 * x + 1") as? Double


Tags: language   interpreter  

Last modified 07 October 2024