Reputation: 167
As the title says i was wondering if there is a way to use ternary operators with multiple statements in Objective C. I know it can be easily done in some other languages like javascript, php, C etc but i couldn't find a solution for Objective C.
I want to implement something like this:
a > b ? ( statement1, statement2, statement3 ) : ( statement1, statement2 );
Basically i just want to avoid a lot of if-else blocks to maintain better code readability. Please also suggest if using ternary operators instead of if-else blocks can harm app performance to a noticeable extent.
Upvotes: 0
Views: 1852
Reputation: 129
The solution for your question (@user3752049) is:
a > b ? ^{ statement1; statement2; statement3;}() : ^{statement1; statement2;}();
Thanks
Upvotes: 0
Reputation: 42588
The Conditional operator ?:
is not a replacement for an if
/else
block. I'm sure you could tweak the logic to make it work, but that would only obscure the meaning more.
My question is, "what are you saving?"
a > b ? ( statement1, statement2, statement3 ) : ( statement1, statement2 );
if (a > b) { statement1; statement2; statement3; } else { statement1; statement2; }
The if
/else
block is a grand total of 7 characters longer.
An even bigger question is, "Can the logic be composed in a better way?"
if
s.Upvotes: 3
Reputation: 52538
You can easily do this; just be aware that the ternary operator can only include expressions, including comma expressions. So your statements can only be expressions, assignments, method calls etc. but no if / return / while and so on. And the ternary operator wants a result, so the last expressions in each group must have the same type; you can just add (void) 0 at the end of each list.
That said, you are most definitely not making your code more readable. Everyone reading it will start swearing at you and doubt your mental sanity. So don't do it.
Upvotes: 0