Sandeep
Sandeep

Reputation: 776

Arithmetic and Conditional Expression evaluator in ios (contains String and Values)

I have three examples in which i have to evaluate expression, Examples as follows,

  1. (x + y +30)

  2. ((p == "Good") && (q == "Morning")) || (r == "10:00")

  3. ((w == "Night") && ( (a + b +30) >100 ) )

Here x, y ,a, and b are integers and p, q, r, and w are Strings.

For #1 I used the DDMathParser library but for #2 and 3 we cannot because DDMathParser does not allow String evaluation.

Requirement is any library or example source code that evaluates above expression contains String and Values.

Please help me to evaluate it.

Any help appreciated.

Upvotes: 0

Views: 214

Answers (1)

Dave DeLong
Dave DeLong

Reputation: 243156

All of these are parseable using NSPredicate or NSExpression. You could use @try...@catch statements to try and run them through +[NSPredicate predicateWithFormat:] or +[NSExpression expressionWithFormat:] and see which one works.

Once you've done that, you could evaluate them against an NSDictionary and see what happens. For example:

NSString *formula = @"((w == \"Night\") && ( (a + b +30) >100 ) )";
NSPredicate *p = [NSPredicate predicateWithFormat:formula];
NSDictionary *object = @{
                         @"w": @"Night",
                         @"a": @42,
                         @"b": @33
                         };

BOOL passes = [p evaluateWithObject:object];
NSLog(@"passes: %@", passes ? @"yes" : @"no"); // logs "yes"

Upvotes: 2

Related Questions