Xcode does not give an error of my (thought-to-be) typo:
NSString *theme = [[NSUserDefaults standardUserDefaults] objectForKey:@"theme"]; NSLog(@"Theme: %@", theme ?: @"Default");
It turns out:
NSLog(@"Theme: %@", theme ?: @"Default");
works same as:
NSLog(@"Theme: %@", theme ? theme : @"Default");
Is the above shorten syntax good for gcc only? Or it is part of Objective-C?
As everyone referred that, It is a way of representing conditional operator if (condition){ true } else { false }
The question mark operator, ?:, is also found in C++. Some people call it the ternary operator because it is the only operator in C++ (and Java) that takes three operands. If you are not familiar with it, it's works like an if-else, but combines operators.
“Question mark” or “conditional” operator in JavaScript is a ternary operator that has three operands. The expression consists of three operands: the condition, value if true and value if false. The evaluation of the condition should result in either true/false or a boolean value.
?: = Question Mark Colon is also called C Ternary Operator.
It's a GNU extension to the conditional expression in C:
From here:
A GNU extension to C allows omitting the second operand, and using implicitly the first operand as the second also:
a = x ? : y;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With