对于单个 if 语句中多个条件的多个条件的循环

For loop for multiple condition over Multiple conditions in single if statement

我见过这样的代码

if ([[dict objectForKey:@"name"] rangeOfString:@“AB”].location != NSNotFound ||
    [[dict objectForKey:@"name"] rangeOfString:@“CD”].location != NSNotFound ||
    [[dict objectForKey:@"name"] rangeOfString:@“EF”].location != NSNotFound ||
    [[dict objectForKey:@"name"] rangeOfString:@“GH”].location != NSNotFound ||
    [[dict objectForKey:@"name"] rangeOfString:@“IJ”].location != NSNotFound ||){
    // do something
   }

我改成了:

NSArray *myArray = [NSArray arrayWithObjects:@“AB”,
                @"CD", @"EF", @"GH", @"IJ", nil];

for (id object in myArray) {
    if ([[dict objectForKey:@"name”] rangeOfString: id].location != NSNotFound){
        // do something
        break;
    }
}

我知道更改代码后可读性更好。它还有其他优点吗?

我没有发现任何实质性差异。您可以通过将字典访问拉出循环来进一步提高可读性和简洁性。

// probably done for you by the compiler, but still prettier to look at...
NSString *name = dict[@"name"];

for (id object in myArray) {
    if ([name rangeOfString:id].location != NSNotFound){
        // do something
        break;
    }
}