How do I use conditionals (e.g. ternary operator) in an NSExpression?

221 Views Asked by At

I'm using an NSExpression to evaluate simple strings such as:

NSExpression(format: "1 + 1").expressionValue(with: nil, context: nil) as? Int == 2

Some of my strings have more complex logic, and I'd like to use a ternary operator. I tried using the traditional ?: syntax, but I get an error:

NSExpression(format: "1 + 1 == 2 ? 'YES' : 'NO'").expressionValue(with: nil, context: nil)

terminating with uncaught exception of type NSException

Is there a way to use a ternary operator assuming the only thing I can change is the string?

2

There are 2 best solutions below

0
On

If you don't want to rely on an (apparently) undocumented expression format then you can create a conditional expression using the

init(forConditional:trueExpression:falseExpression:)

constructor (documentation). Example:

let expr = NSExpression(forConditional: NSPredicate(format: "1 + 1 == 2"),
                        trueExpression: NSExpression(forConstantValue: "YES"),
                        falseExpression: NSExpression(forConstantValue: "NO"))
0
On

Yes. I'm not sure where the documentation lives, but I found some obscure references to a TERNARY function. If you try it out within an NSExpression, it works:

NSExpression(format: "TERNARY(1 + 1 == 2, 'YES', 'NO')").expressionValue(with: nil, context: nil) as? String == "YES"

It looks like the format is:

TERNARY(<predicate>, <trueValue>, <falseValue>)