Reputation: 776
I have three examples in which i have to evaluate expression, Examples as follows,
(x + y +30)
((p == "Good") && (q == "Morning")) || (r == "10:00")
((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
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