Objective-C Syntactical Question
Just doing some research on searching for a character or word within a NSString and I came across this code snippet (which works like a charm):
return [sourceString rangeOfString:searchString].location != NSNotFound;
Am I right in thinking that the above 开发者_StackOverflow中文版code is functionally identical to:
NSRange range = [sourceString rangeOfString:searchString];
if (range.location == NSNotFound)
return NSNotFound;
else
return range.location;
Obviously the first snippet is much cleaner but I'm not clear on the != NSNotFound
part. Could someone explain that to me?
The !=
operator evaluates to a boolean, so it's equivalent to:
NSRange range = [sourceString rangeOfString:searchString];
if (range.location == NSNotFound)
return NO;
else
return YES;
Which is the same as:
NSRange range = [sourceString rangeOfString:searchString];
BOOL didNotFind = (range.location == NSNotFound);
return !didNotFind;
Actually no, it's equivalent to:
NSRange range = [sourceString rangeOfString:searchString];
if (range.location == NSNotFound)
return NO;
else
return YES;
Which can be written shorter as:
NSRange range = [sourceString rangeOfString:searchString];
BOOL result = range.location != NSNotFound;
return result;
精彩评论