Phrase

public class Phrase : Equatable

Parse and evaluate a boolean expression.

Expressions consist of an expression string and a context to set parameters/replace variables.

Example:

let expression = try Phrase("list != nil && list.count > 3")
expression.context = [
   "list": [1,2,3,4,5]
]
if try expression.evaluate() {
    ...
} else {
    ...
}
  • Evaluation context, holding values for variable names

    Example:

    try Phrase("list.count > 3")
    expression.context = [
        "list": [1,2,3,4,5]
    ]
    

    Declaration

    Swift

    public var context: Context
  • Create a new instance of Phrase based on the given expression.

    Evaluating an Abstract Syntax Tree (AST) consists of three steps:

    1. Finding the lexems (smallest known valid tokens) using a Lexer (eg. split by spaces),
    2. Parse the tokens into tree nodes using a Parser (e.g. && means logically and).
    3. Evaluate the AST tree with optional variable values into a single boolean value using a Evaluator.

    Algorithm runs linearly in O(n).

    Throws

    PhraseError, if the expression is invalid and can not be parsed

    Declaration

    Swift

    public init(_ expression: String) throws

    Parameters

    expression

    Expression to be converted into a AST

  • Evaluates the Abstract Syntax Tree (AST) of this expression, using the current context.

    Throws

    if the evaluation fails, see Evaluator.evaluate for more details.

    Declaration

    Swift

    public func evaluate() throws -> Bool

    Return Value

    Boolean result value of the AST based on the current context.

  • Checks if two instances of Phrase equal.

    Declaration

    Swift

    public static func == (lhs: Phrase, rhs: Phrase) -> Bool

    Parameters

    lhs

    One instance of Phrase

    rhs

    Another instance of Phrase

    Return Value

    true if the tree and the context equal, otherwise false