Objective-C Tricks: #1 Ternary Operations

Objective-C is a reflective and powerful object-oriented language. When first starting (or looking) at the syntax, many react fearfully to the verbosity and square brackets. Many rarely get beyond the basics they learned when making their first app, but there are many unused abilities in Objective-C.

Ternary Operations with Objective-C objects

Most people are familiar with ternary operations. For example:

1
NSString *myString = [self isHighlighted] ? @"Highlighted" : @"Not Highlighted";

Similar to this behavior in C:

1
int i = 1 ? : 0;

Objective-C supports omitting the true side of the ternary operator when working with objects. Consider a case where you need to set a string depending on whether another string is nil or not. You might try:

1
2
3
4
5
6
NSString *myString = nil;
if ([self otherString] != nil) {
  myString = [self otherString];
} else {
  myString = kSomeConstantString;
}

We can quickly clean this scenario up (down to one line, even). First, we remove the check against nil. When checking the state of an object ( if (obj != nil) { ... }), nil is a false statment and non-nil is a true statement. Therefore, we can update this to ( if (! obj) { ... } ). We can then expand that into a ternary operation.

1
NSString *myString = [self otherString] ? [self otherString] : kSomeConstantString;

We can go a bit further in this scenario, however. Since the object we are checking is also the true side of the ternary operation, we can omit it.

1
NSString *myString = [self otherString] ? : kSomeConstantString;

UPDATE: Another thing that makes this useful is that the message to self is only sent once. (Thanks to @bmf making this point.)


Comments