简体   繁体   中英

Ternary operator with nothing in 'if' condition

What does the following code do?

return obj ? : [NSNull null];

From my understanding of ternary operations it would be equivalent to:

if (!obj)
    return [NSNull null];

But what gets returned if (obj) ? Does it fall through to still return [NSNull null] ?

If obj is True , obj is returned.

return obj ? : [NSNull null];

is equivalent to:

id x = obj;
if (x) {
    return x;
else {
    return [NSNull null];
}

As long as obj has no side effects it is logically equivalent to:

return obj ? obj : [NSNull null]

The code...

return foo ? : bar;

Will return the same value as...

return foo ? foo : bar;

The difference is that the first method only inspects the foo value once.

It is better to use the first in several cases.

For instance, creating an object...

// this would create two objects, one to check and the other to return
return [MyObject objectWithSomeParam:param] ? [MyObject objectWithSomeParam:param] : bar;

or running an expensive function...

// the expensive function here is run twice
return [self someExpensiveFunction] ? [self someExpensiveFunction] : bar;

Both of these would benefit from using

return foo ?: bar;

Essentially, if the validation object is the same as the return object for true then use the shortened version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM