swiftnspredicatensexpression

Swift 4 NSExpression with Multiple Functions


So I have a string formula that let's say is:

let testValue = 10
let formula = "(max(testValue - 20,0) * 14) + testValue - max(testValue - 20,0)"

I can do simple arithmetic, multiplication, division, subtracts, ect but how would I combine the Max function into this string?

I was thinking I would have to change max to something that I can substring and then do each function individual and loop through the instances, but is there a better way or is that the way to do it? Like |@Max(x,y)|.

Also, is there a specific syntax as I couldn't find any examples of using Max, Min, Sum, Avg, ect - maybe I am just not understanding the documentation.

//Current way
extension String {
    var expression: NSExpression {
        return NSExpression(format: self)
    }
}

let results = formula.expression.expressionValue(with: nil, context: nil) as? Int

Solution

  • I figured it out.

    For anyone who needs this - you can take any string and use:

    functionName(x) for most of the functions like sqrt, multiplyby, trunc, ceiling, ect

    And then for the six with multiple variables (max, min, count, average, sum, and one other I forget) you use functionName({x,y}).

    All can be used in a string with expressionValue(with: nil, context: nil)