Question

A fairly common pattern is: if some object exists, I want to use that object in my code, but if it is not set, I want to fail over to some default value.

Using a background image as an example, and assuming some UIImage *backgroundImage property that may or may not be set when this code is evaluated, the verbose way to do this might be:

UIImage *image;
if (self.backgroundImage) {
    image = self.backgroundImage;
} else {
    image = [UIImage imageNamed:@"default"];
}

A more compact method is:

UIImage *image = (self.backgroundImage) ? self.backgroundImage : [UIImage imageNamed:@"default"];

My question is: is there an even more short-hand way to accomplish this?

Something like:

UIImage *image = self.backgroundImage || [UIImage imageNamed:@"default"];

I can't find anything in the Clang Literals documentation, but this sort of short-hand may not actually be considered a 'Literal', or even be part of Clang for that matter.

(I'm also unsure where the "(truth statement) ? id1 : id2" syntax is documented for Clang/LLVM; knowing where the exhaustive set of those short-hand statements are would also be grand!)

Was it helpful?

Solution

UIImage *image = (self.backgroundImage) ? self.backgroundImage : [UIImage imageNamed:@"default"];

My question is: is there an even more short-hand way to accomplish this?

Yes; just omit the middle term:

UIImage *image = self.backgroundImage ? : [UIImage imageNamed:@"default"];

Documented here.

And in Swift there is now the ?? operator which does just what the ?: operator does in Objective-C.

OTHER TIPS

Absolutely the most short way in this case is:

UIImage *image;
if (!(image = self.backgroundImage)) image = [UIImage imageNamed:@"default"];

The if statement check if is self.backgroundImage is nil, and in the same time assign it to image. If is nil, assign the new object to image.

I recently discovered that there is a GNU extension to C that allows omitting the second operand of the conditional operator (ternary if):

UIImage *image = self.backgroundImage ?: [UIImage imageNamed:@"default"];

https://stackoverflow.com/a/3319144/3617012

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top