Last Updated: February 25, 2016
·
794
· isutton

Ternary without left hand side operator

Ternaries can be used without the left hand side operator, making the following:

on ? [something start] : [something stop];

terser than:

if (on) {
    [something start];
}
else {
    [something stop];
}

I guess it is wise to mention it should be used on simple cases, where the usual if/else dance feels inelegant. One example is to perform some action depending on the state of a UISwitch:

- (void)switchChanged:(id)sender
{
    ((UISwitch *)sender).on ? [self start] : [self stop];
}