iOS - How to use NSExpression with one unknown parameter

1.6k Views Asked by At

I'm using NSExpression to evaluate a formula in a string.

Example -

NSString *formula = @"7+11";
NSExpression *exp = [NSExpression expressionWithFormat: formula];
NSNumber *expResult = [exp expressionValueWithObject:nil context:nil];

Everything works just fine but...

What if I have the following formula "7+x=18"? How can I evaluate this formula and find "x" and get the result 11?

1

There are 1 best solutions below

0
On
NSString *formula = @"12.845*x+(-0.505940)";
float x = 12.0;

NSExpression *expr = [NSExpression expressionWithFormat:formula];
NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:
                          [NSNumber numberWithFloat:x], @"x", nil];

float result = [[expr expressionValueWithObject:object context:nil] floatValue];
NSLog(@"%f", result);
// Output: 153.634064

Original Answer here