Ternary operator

Ternary operators are a concise way to write conditional statements that have two possible outcomes. Rather than writing a longer series of if/then/else statements you can write one line that makes it clear what the two choices are.

In this example from iOS, I use a string for direction—either clockwise or counterclockwise—and translate it to a number for use in the formula. That way I don’t have to remember whether -1 is clockwise or counterclockwise when calling the method. I can use natural language to call the method and let the ternary operator take care of the conversion to the value I need in my formula. And I can change my formula at a later date without having to go back and find all the method calls.

Here’s the method call and the operator


- (void)spin:(NSString *)direction withDuration:(float)duration withScale:(float)scale {
    
    int rotation = ([direction isEqualToString:@"clockWise"] ? 1 : -1);

And then use rotation later to determine which way the object rotates


view.transform = CGAffineTransformRotate(CGAffineTransformScale(transform, 1.0, 1.0), rotation * 2*M_PI/3);

Here’s another example, where I want to pass in a value, but make sure that it isn’t less than one. In this case I’m passing in an integer and rather than doing a series of complicated if/then/else statements I just put the ternary operator in where the integer goes.


self.showRewards = [[ShowRewards alloc] initWithParentView:self.view withLevel:(rewardLevel > 0 ? rewardLevel : 1) ];

I also use it in PHP code for plurals. Something like this is what I use.

$text = "The update was successful. $recordsUpdated " . ($recordsUpdated > 1 ? 'records were updated.' : 'record was updated.');
echo $text;

And I use it to write one set of code that works for two inputs. In this case I have a page that displays all of the titles that are downloadable from Gumroad. Since people are only interested in the Mac or Windows version, I put them on two different pages—but I use the same code. The first part reads in the page type from the URL and puts up a title for Macintosh or Windows.


if ( isset($_GET['page']) ) { $MacWin  = mysql_real_escape_string($_GET['page']); }  else { $MacWin  = 'Win';} 

echo "<div id='wideMargins'>";
$MacintoshWindows = ($MacWin == 'Mac' ? 'Macintosh' : 'Windows');
echo "<h2 class='NewSection'>Download $MacintoshWindows Compatible Titles from Gumroad</h2>";

Then in the SQL statements I pull the appropriate titles. My column names are GumroadURL_Mac and GumroadURL_Win so the $MacWin variable is substituted into the SELECT statement.


$qry = "SELECT *
        FROM product, product_instance
        WHERE product.id = product_id
        AND GumroadURL_$MacWin IS NOT NULL
        ORDER BY name";

I use a full ternary operator to get the right column from the row.


for ($i = 0; $i < $numRows; $i++) {
    $row   = $res->fetch_array();
    $name = $row['name'];
    $tagline = $row['tagline'];
    $GumroadURL = ($MacWin == 'Mac' ? $row['GumroadURL_Mac'] :$row['GumroadURL_Win']);

As you can see, it makes the code much easier to read and in this example, I have one page of code that easily generates two web pages.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.