Reputation: 9243
I'm finding that the current production version of Xcode is giving me an error when I use the ternary operator like so:
//If address.title is not nil, leave it alone. Else, set it to @"".
address.title ?: [address setTitle:@""];
address.street ?: [address setStreet:@""];
When I use a beta preview for Xcode 5.1, i get no such warning. What gives?
Upvotes: 0
Views: 146
Reputation: 539695
"Conditionals with Omitted Operands" are a GCC extension (also understood by Clang), and
address.title ? : [address setTitle:@""];
is equivalent to
address.title ? address.title : [address setTitle:@""];
with the only difference that address.title
is evaluated only once.
Now the second operand has pointer type (NSString *
) and the
third operator has void
type. In this case the result type of the conditional
expression would be void
, but ARC does not allow the implicit conversion of NSString *
to void
. This would compile:
address.title ? (void)0: [address setTitle:@""];
but, as Merlevede already said, it is much clearer to use an explict if-statement.
If the compiler contained in the beta preview for Xcode 5.1 does not give an error then it could be a bug in the compiler. Of course it could also be another language extension that I do not know of!
Upvotes: 1
Reputation: 8170
Your syntax is wrong
address.title ?: [address setTitle:@""];
should be
address.title = (address.title)? address.title : @"";
// or
[address setTitle:((address.title)? address.title : @"")];
The general syntax is
var = (condition) ? value_if_true : value_if_false; // general syntax
In your case it would be better to do
if (!address.title)
address.title = @"";
Upvotes: 0