Why does this work?! (Challenge 2)


#1

I am unsure why what I have done works to find all the names that are also words (and for some strange reason a bunch names that happen to start with a lowercase?). What I tried to do was compare the two lists, first looking for all the proper names in both files using caseInsensitive, AND (shown as &&) compare them to see which ones were NOT equal when compared with isEqualToString. However in my code, it looks like I have it so that it IS equal both with caseInsensitiveCompare and using isEqualToString and it produces the proper results. Any ideas why this seems to work?

            for (NSString *n in names){
                 for (NSString *w in words) {
                     if (([n caseInsensitiveCompare: w ] == NSOrderedSame) && ([n isEqualToString:w] == NSOrderedSame))  
                         NSLog(@"%@ and %@", w, n);
                }
            }

#2

[quote=“jemicha”]I am unsure why what I have done works to find all the names that are also words (and for some strange reason a bunch names that happen to start with a lowercase?). What I tried to do was compare the two lists, first looking for all the proper names in both files using caseInsensitive, AND (shown as &&) compare them to see which ones were NOT equal when compared with isEqualToString. However in my code, it looks like I have it so that it IS equal both with caseInsensitiveCompare and using isEqualToString and it produces the proper results. Any ideas why this seems to work?

[code]
for (NSString *n in names){
for (NSString *w in words) {
if (([n caseInsensitiveCompare: w ] == NSOrderedSame) && ([n isEqualToString:w] == NSOrderedSame))
NSLog(@"%@ and %@", w, n);
}
}

[/code][/quote]

caseInsensitiveCompare returns an NSComparisonResult.
isEqualToString returns a BOOL.

NSOrderedSame is from the NSComparisonResult, and is equal to the integer 0 (which is the same as the BOOL false/NO).
Therefore… In the 2nd half of your comparison, you are comparing the BOOL result to 0.
So, your statement is basically saying “are they the same string when compared case insensitive, and are they NOT equal to each other?”


#3

I see now why that makes sense, thanks for the explanation.

The double negative thing makes it difficult to read and understand though, I came up with something that makes MUCH more sense to me and it seems to work:

for (NSString *n in names){
                 for (NSString *w in words) {
                     if (([n caseInsensitiveCompare: w ] == NSOrderedSame) && (![n isEqualToString:w]))  
                         NSLog(@"%@ and %@", w, n);
                }
            }

the change being: ![n isEqualToString:w]

Thanks again for the reply.