I tried to shorten my code, from :
if(i== x || i == y || i == z )
to
if (i == ( x || y || z ))
I know this way is wrong because I got incorrect i in log.
However, is there any method to shorten the code in objective-C ?
I tried to shorten my code, from :
if(i== x || i == y || i == z )
to
if (i == ( x || y || z ))
I know this way is wrong because I got incorrect i in log.
However, is there any method to shorten the code in objective-C ?
You could use a
switch
statement, but that doesn't really buy you a lot with only 2-3 values.It'd be more of a savings if the thing you were checking was more complex or you had a lot more options.
if there is a higher probability that
x==i
thany==i
then it's better to write it asx==i || y==i
as opposed toy==i || x==i
because if the first statement evaluates to true, the second one is not evaluated (it's shortcircuited)As for your question where you compared 50 values.
Make an NSMutableArray composed of those 50 variables... then use this code.
Use this code:
Works like a charm!
If you want to check each value separately you could use a while loop or a for loop:
The parts below are for others who needed different answers to this question:
There could be ways to shorten your whole conditional statement if we had the rest of the code... as for shortening just the "OR" part I'm not sure how...
But something like:
could become:
or... something like:
could become:
Since I often use conditional statements with numeric values I often use a shortcut where if a conditional statement is true it is equivalent to 1 whereas if it is false it is equivalent to 0, because of this I can say things like
If i is equal to x or y it will return true (which is "1") which will return 1*(z+w) or (z+w) but if the condition is false it returns "0" which returns 0*(z+w) or 0.
Final notes: *There could be mathematical ways to represent a function hat returns the desired results you want... for example if x = -2 and y = 2 than instead of checking if i==x or i==y just check if abs(i) == y (*abs being the absolute value)
If you are using TONS of variables you could do something like this :)
If you want to check a lot of objects you could use
NSArray
andindexOf
method:Computers work with digital signals. All natural operations for computers are binary.
If you want to compare three things, you'll have to use two binary comparisons to make it nice for the computer.
Also you need to realize that shorter code is not necessarily faster. Often, it is just a shortcut notion for the author.
So why do you think you need to shorten this expression further?