Ternary Operator With Objective-C Objects

I previously wrote about C ternary operatar which provides an opportunity to write code that is “short-hand” if you will. A ternary operator is one that accepts three arguments, more on this below.

This is the traditional form of an if/else:

int x = 5;
 
...
 
if (x > 1)
  y = x;
else
  y = -1;

And here is a version using the ternary operators:

int y = x > 1 ? x : -1;

Ternary Operator and Objective-C Objects

You can do the same using Objective-C objects, however, there is one interesting twist, which I’ll cover in a moment.

The simple method below displays an error message to the console. If the msg parameter is not nil, the msg is concatenated onto the string “Message:”. If the msg is nil, there is a complete error message created stating there was an unknown error:

- (void)displayErrorMessage:(NSString *)msg
{
  NSString *msgFullString;
 
  if (msg != nil)
    msgFullString = [NSString stringWithFormat:@"Message: %@", msg];
  else
    msgFullString = @"Message: Unknown error 1";
 
  NSLog(@"%@", msgFullString);
}

Let’s call the method twice as shown below:

[self displayErrorMessage:@"Network error"];
[self displayErrorMessage:nil];

The output will be as follows:

Message: Network error
Message: Unknown error

The shorted version using ternary operators is below:

- (void)displayErrorMessage:(NSString *)msg
{
  NSString *msgFullString = [NSString stringWithFormat:@"Message: %@", msg ? msg  : @"Unknown error"];
 
  NSLog(@"%@", msgFullString);
}

The code above replaces the if/else with the ternary ? : operators – if msg is !nil append msg to the “Message” string, otherwise shown the output “Unknown error”

Objective-C Ternary Operator Tricks

One unique ability of using the ternary operand with objects is that the code can be shorted even further. If the value being checked is also the value after the ternary operator, the value can be omitted from the operation:

The final result looks as follows (notice ‘msg’ is no longer present after the ?)

- (void)displayErrorMessage:(NSString *)msg
{
  // Even shorter version, when
  NSString *msgFullString = [NSString stringWithFormat:@"Message: %@", msg ? : @"Unknown error"];
 
  NSLog(@"%@", msgFullString);
}
  1. This is very cool. How did you find this? Is it documented somewhere?

    It seems that this ternary shortcut works for non-objects as well.

    int i = 0;
    int x = 9;

    x = i ? : 5;
    NSLog(@”%@”, @(x));

    i = 3;
    x = i ? : 5;
    NSLog(@”%@”, @(x));

Comments are closed.