Jakub
Jakub

Reputation: 13860

Question mark as "if" notation

I'm aware of using syntax like this:

(something) ? TRUE : FALSE

But what if i want to return checking variable? For example:

if([myVar objectForKey:objectName])
    return [myVar objectForKey:objectName]
else
    return -1;

Is there a syntax like first line of code here that do that?

Of course i know that i can simply do something like:

([myVar objectForKey:objectName]) ? return [myVar objectForKey:objectName] :  return -1;

But this is AFAIK very ugly solution

Upvotes: 1

Views: 752

Answers (3)

andyvn22
andyvn22

Reputation: 14824

There is an easy way to use the ternary operator (that's what that ? : syntax is called) in a return statement:

return [myVar objectForKey:objectName] ? [myVar objectForKey:objectName] : -1;

And it can be made more concise with a quick variable:

id result = [myVar objectForKey:objectName];
return result ? result : -1;

However! What's your return type here? There's a possibility you'll return [myVar objectForKey:objectName], which is of type id, or that you'll return -1, which is of type NSInteger. One's an Objective-C object and the other is a C primitive--something seems fishy with this specific example.

Upvotes: 2

walkytalky
walkytalky

Reputation: 9543

Off the top of my head I think this should work (EDIT: but see andyvn22's answer re: return types):

id foo;
return (foo = [myVar objectForKey:objectName]) ? foo : -1;

As a general rule, though, you're almost always better off using an easy to understand notation than one that is slightly more concise but cryptic.

Upvotes: 2

user1118321
user1118321

Reputation: 26395

I'm not sure what you're asking, but you could always do something like:

id foo = [myVar objectForKey:objectName];
return (foo) ? foo : -1;

or

return [myVar objectForKey:objectName] ? [myVar objectForKey:objectName] : -1;

Upvotes: 2

Related Questions