objective c - Replace If statement with ternary operator -



objective c - Replace If statement with ternary operator -

i'm trying figure out if it's possible replace next code simpler code, using ternary operator.

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];

something this:

self.notalabel.text = [nsstring stringwithformat:@"%@ / %@", [nf stringfromnumber:[nsnumber numberwithfloat:[self.pesonota[@"nota"] floatvalue]]] ? : @"nd", [nf stringfromnumber:[nsnumber numberwithfloat:[exercicio[@"notacomunidade"] floatvalue]]] ? : @"nd"];

the sec code doesn't give me expected result, returns 0 in case first look false, want homecoming string.

anyway, don't think possible cut down code, anyways, it's worth seek since utilize lot.

first of if utilize code lot should dedicate little helper function it. sec thing, illustration missing conditions , semantics different desired result:

self.notalabel.text = [nsstring stringwithformat:@"%@ / %@", [nf stringfromnumber: [nsnumber numberwithfloat:[self.pesonota[@"nota"] floatvalue]]] ? /* missing status */ : @"nd", [nf stringfromnumber: [nsnumber numberwithfloat:[exercicio[@"notacomunidade"] floatvalue]]] ? /* missing status */ : @"nd" ];

it should like:

self.notalabel.text = [nsstring stringwithformat:@"%@ / %@", [self.pesonota[@"nota"] floatvalue] > 0.0 ? // status [nf stringfromnumber:[nsnumber numberwithfloat:[self.pesonota[@"nota"] floatvalue]]] // true case : @"nd" // false case , [exercicio[@"notacomunidade"] floatvalue] > 0.0 ? // status [nf stringfromnumber:[nsnumber numberwithfloat:[exercicio[@"notacomunidade"] floatvalue]]] // true case : @"nd" // false case ];

which quite unreadable in case. mean, can declare local variables right avoid messy code:

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" ];

objective-c c if-statement operators ternary-operator

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

c# - Create a Notification Object (Email or Page) At Run Time -- Dependency Injection or Factory -

Set Up Of Common Name Of SSL Certificate To Protect Plesk Panel -