Question

I have a code like this:

MyClass *object = [self nextValidObject];

The method nextValidObject will return nil if there is no new object to return or the next object available.

After that I have a value I have to fetch from an array, something like

NSArray *myArray = @[@"aaa", @"bbb"];

I want to fetch "aaa" if object is nil and "bbb" if it is not.

I know, I can do this:

NSString *myString = object ? @"aaa" : @"bbb";

or

NSString *myString = object ? myArray[0] : myArray[1];

but I was thinking on something like

NSString *myString = myArray[ ... some magic here ... ];

by some magic I wonder if there is a way to cast (I don't know if this is the correct word) 0 to nil and 1 to not nil, so I can use object there.

Was it helpful?

Solution

If you don't want to branch you could do something like this:

NSString *myString = myArray[(NSUInteger)ceil((double)(intptr_t)(__bridge void *)object / ((double)(intptr_t)(__bridge void *)object + 1))];

There is probably a better way than this, but I can't think right now. It shows the idea though.

Actually, having thought about this the following will work and be more readable:

myArray[(intptr_t)(__bridge void *)object && 1];

Branching isn't that bad though, unless there are specific reasons why you want to avoid branching.

OTHER TIPS

Although, there are explicit if-clauses in

NSArray myString = object ? @"aaa" : @"bbb";

is called a ternary operator, which is in many programming languages a "shortcut" for if clauses. You could use casts:

NSObject *object = nil; 
int i = (int)(object || 0); // i = 0 
// if object is not nil i = 1

But I would not recommend it to use this in software development. There is a reason why if-clauses are used and helpful. :-) I do not understand why you want to avoid if-clauses.

Don't know why you want to do this but you can go

int i = 1;
NSString *myString;
do {
    myString = myArray[i--];
} while (object && i >= 0);

No ifs..

Try this:

NSString *myString = myArray[ (nextValidObject ? 1 : 0) ];

Not all that different from what you are already doing, but at least the decision happens inside the square brackets, as you seem to want. Not magic, but it's what I would probably write...

Objective-C is C and in C the relational and equality operators return an integer value - 1 if the condition is true, 0 if it is false. So the expression:

object != nil

has the value 1 if object is not nil, and 0 if it is. Nothing more complicated is required.

You have NSArray *myArray = @[@"aaa", @"bbb"];

You want myArray[1], which equals "bbb", when object is nil.

pseudocode:

if object equal nil
    index := 1
else
    index := 0
myString := myArray[index]

Objective C:

NSInteger index = (object != nil);
NSString *myString = [myArray objectAtIndex:index];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top