Arian Faurtosh
Arian Faurtosh

Reputation: 18511

Can someone explain this objective C statement

I don't understand what is going on here, I am trying to use regex and I am really confused by the following.

BOOL isMatch = match != nil;

The full code is

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[a-z0-9_]" options:NSRegularExpressionCaseInsensitive error:nil];
NSTextCheckingResult *match = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
BOOL isMatch = match != nil;

Upvotes: 0

Views: 60

Answers (4)

Ant P
Ant P

Reputation: 25221

It might be clearer if we use some parentheses:

BOOL isMatch = (match != nil);

That is, if match is not nil, isMatch will be true (YES).

Upvotes: 2

rmaddy
rmaddy

Reputation: 318804

It's a basic C statement involving a variable assignment (on the left of the =) and an expression (on the right of the =).

Let's start with the right side:

match != nil;

This expression is evaluated. The != operator (not-equal or unequal) evaluates to either true or false. If match has been assigned to a non-nil value, it is true. If it has not been assign a nil value, it is false.

This true or false result is then assigned to the BOOL variable. A true result is YES and false result is NO.

So in English, the statements says:

If match has a non-nil value, isMatch is YES, otherwise it is NO.

Upvotes: 1

Megan
Megan

Reputation: 569

BOOL isMatch = match != nil;

is a shorter way to write

BOOL isMatch;
if(match != nil)
{
  isMatch = YES; // You found a match!
}
else
{
  isMatch = NO; // No match found :(
}

Upvotes: 1

Fonix
Fonix

Reputation: 11597

break it up into bits, think about if you put match != nil into an if statement, but instead assigning the result to a bool

Upvotes: 0

Related Questions