Dave Chambers
Dave Chambers

Reputation: 2563

Assignment in ternary conditional operator produces "Expression is not assignable" error

Can anybody tell me why the following was okay:

if (newEditingMode) {
    dayView.dayViewIsInEditingMode = YES;
}
else{
    dayView.dayViewIsInEditingMode = NO;
}

But the following gave the error Expression is not assignable:

newEditingMode ? dayView.dayViewIsInEditingMode = YES : dayView.dayViewIsInEditingMode = NO;

Upvotes: 1

Views: 2057

Answers (2)

Metabble
Metabble

Reputation: 11841

You can use parentheses and it will compile. Try the following.

newEditingMode ? (dayView.dayViewIsInEditingMode = YES) : (dayView.dayViewIsInEditingMode = NO);

However, you shouldn't perform assignment inside the ternary conditional itself; you should use this instead.

dayView.dayViewIsInEditingMode = newEditingMode ? YES : NO;

Or, in this case, you can just drop the ternary altogether, since it is redundant.

dayView.dayViewIsInEditingMode = newEditingMode;

Upvotes: 5

rdelfin
rdelfin

Reputation: 816

The ternary operator does very strange things to the order of operations. Here is a posible solution which might help.

dayView.dayViewIsInEditingMode = (newEditingMode ? YES : NO);

Seeing what you are doing, you could alternatively write it like so:

dayView.dayViewIsInEditingMode = newEditingMode;

Upvotes: 3

Related Questions