2014-06-23 44 views
0

我想弄清楚是否有可能用简单的代码,使用三元运算符替换下面的代码。替换如果语句与三元运算符

if ([self.pesoNota[@"nota"] floatValue] > 0.0) { 
     suaNota = [nf stringFromNumber:[NSNumber numberWithFloat:[self.pesoNota[@"nota"] floatValue]]]; 
    } 
    else { 
     suaNota = @"ND"; 
    } 
    if ([exercicio[@"notaComunidade"] floatValue] > 0.0) { 
     notaComunidade = [nf stringFromNumber:[NSNumber numberWithFloat:[exercicio[@"notaComunidade"] floatValue]]]; 
    } 
    else { 
     notaComunidade = @"ND"; 
    } 

    self.notaLabel.text = [NSString stringWithFormat:@"%@/%@", suaNota, notaComunidade]; 

事情是这样的:

self.notaLabel.text = [NSString stringWithFormat:@"%@/%@", [nf stringFromNumber:[NSNumber numberWithFloat:[self.pesoNota[@"nota"] floatValue]]] ? : @"ND", [nf stringFromNumber:[NSNumber numberWithFloat:[exercicio[@"notaComunidade"] floatValue]]] ? : @"ND"]; 

第二个代码不给我预期的结果,它的情况下,返回0第一个表达式是假的,我希望它返回一个字符串。

无论如何,我不认为有可能减少此代码,但无论如何,这是值得一试,因为我使用了很多。

+0

“因为我使用了很多” - 所以为什么不把它放入它自己的函数/方法? – Kreiri

+2

更少的行!=更简单... –

+0

非常感谢,这肯定是一个选项,但问题是更概念化,我只想知道是否有可能减少此代码。对我而言,更少的线==简单。 :) – Jorge

回答

1

首先,如果你使用这个代码很多,你应该专门给它一个小的帮助函数。第二件事情,你的例子是缺失的条件和语义是从你期望的结果完全不同:

self.notaLabel.text = 
[NSString stringWithFormat:@"%@/%@", 
    [nf stringFromNumber: 
     [NSNumber numberWithFloat:[self.pesoNota[@"nota"] floatValue]]] ? 
     /* missing condition */ : 
     @"ND", 

    [nf stringFromNumber: 
     [NSNumber numberWithFloat:[exercicio[@"notaComunidade"] floatValue]]] ? 
     /* missing condition */ : 
     @"ND" 
]; 

它应该是这样的:

self.notaLabel.text = 
[NSString stringWithFormat:@"%@/%@", 
    [self.pesoNota[@"nota"] floatValue] > 0.0 ? // condition 
    [nf stringFromNumber:[NSNumber numberWithFloat:[self.pesoNota[@"nota"] floatValue]]] // true case 
    : @"ND" // false case 
    , 
    [exercicio[@"notaComunidade"] floatValue] > 0.0 ? // condition 
    [nf stringFromNumber:[NSNumber numberWithFloat:[exercicio[@"notaComunidade"] floatValue]]] // true case 
    : @"ND" // false case 
]; 

这是在任何情况下,相当不可读。我的意思是,你可以声明局部变量的权利,以避免乱码:

NSNumber* notaValue = self.pesoNota[@"nota"]; 
NSNumber* notaComunidade = exercicio[@"notaComunidade"]; 

self.notaLabel.text = [NSString stringWithFormat:@"%@/%@", 
    [notaValue floatValue] > 0 ? [nf stringFromNumber:notaValue] : @"ND", 
    [notaComunidade floatValue] > 0 ? [nf strungFromNumber:notacomunidadate] : @"ND" 
]; 
+0

正是我在找的东西。谢谢。 – Jorge

1

你的代码中包含重复的,你可以提取到另一种方法:

- (NSString *)floatStringOrNDForNumber:(NSNumber *)number numberFormatter:(NSNumberFormatter *)numberFormatter { 
    return ([number floatValue] > 0.0f) ? [numberFormatter stringFromNumber:number] : @"ND"; 
} 

然后你有一个很干净的,可理解的几行代码:

suaNota = [self floatStringOrNDForNumber:self.pesoNota[@"nota"] numberFormatter:nf]; 
notaComunidade = [self floatStringOrNDForNumber:exercicio[@"notaComunidade"] numberFormatter:nf]; 
self.notaLabel.text = [NSString stringWithFormat:@"%@/%@", suaNota, notaComunidade];