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?
If you don't want to rely on an (apparently) undocumented expression format then you can create a conditional expression using the
constructor (documentation). Example: