这个巨大的if语句感觉很难......你会如何在Objective C中做到这一点

时间:2011-02-01 19:48:03

标签: iphone objective-c cocoa-touch

for (NSString *metarComponent in self.readingComponents) {
    if ( [metarComponent hasPrefix:@"+"]
         || [metarComponent hasPrefix:@"-"]
         || [metarComponent hasPrefix:@"VC"]
         || [metarComponent hasPrefix:@"MI"]
         || [metarComponent hasPrefix:@"PR"])
         || [metarComponent hasPrefix:@"BC"])
         || [metarComponent hasPrefix:@"DR"])
         || [metarComponent hasPrefix:@"BL"])
         || [metarComponent hasPrefix:@"SH"])
         || [metarComponent hasPrefix:@"TS"])
         || [metarComponent hasPrefix:@"PZ"])
         || [metarComponent hasSuffix:@"DZ"])
         || [metarComponent hasSuffix:@"RA"])
         || [metarComponent hasSuffix:@"SN"])
         || [metarComponent hasSuffix:@"SG"])
         || [metarComponent hasSuffix:@"IC"])
         || [metarComponent hasSuffix:@"PL"])
         || [metarComponent hasSuffix:@"GR"])
         || [metarComponent hasSuffix:@"GS"])
         || [metarComponent hasSuffix:@"UP"])
         || [metarComponent hasSuffix:@"BR"])
         || [metarComponent hasSuffix:@"FG"])
         || [metarComponent hasSuffix:@"FU"])
         || [metarComponent hasSuffix:@"VA"])
         || [metarComponent hasSuffix:@"DU"])
         || [metarComponent hasSuffix:@"SA"])
         || [metarComponent hasSuffix:@"HZ"])
         || [metarComponent hasSuffix:@"PY"])
         || [metarComponent hasSuffix:@"PO"])
         || [metarComponent hasSuffix:@"SQ"])
         || [metarComponent hasSuffix:@"FC"])
         || [metarComponent hasSuffix:@"SS"])
         || [metarComponent hasSuffix:@"DS"]) {     
            [rawWeatherStrings addObject:metarComponent];
        }
}

4 个答案:

答案 0 :(得分:5)

我会创建一个前缀的NSSet和一个后缀的NSSet,然后在这些集合上使用containsObject和第一个字符(在查看你的前缀集后也是前两个字符),最后两个字符从有问题的字符串中拉出来,检查集合。查找速度非常快。

答案 1 :(得分:1)

一系列前缀和后缀数组以及两个for循环都应该这样做。

答案 2 :(得分:0)

构建前缀/后缀的常量表和指示它的标志,然后遍历表以检查它是否具有前缀或后缀。

答案 3 :(得分:0)

NSArray *prefixes = [NSArray arrayWithObjects: @"+", @"-", ..., @"PZ", nil];

NSArray *suffixes = [NSArray arrayWithObjects: @"DZ", @"RA", ..., @"DS", nil];

for (NSString *metarComponent in self.readingComponents) {
    for (NSString *prefix in prefixes)
        if ( [metarComponent hasPrefix:prefix])
             [rawWeatherStrings addObject:metarComponent];
    for (NSString *suffix in suffixes)
        if ( [metarComponent hasSuffix:suffix])
             [rawWeatherStrings addObject:metarComponent];
}