How to properly use conditionak operator in Swift

115 views Asked by At

I want to rewrite the below code to use the conditional operator:

if indexPath.row == 0 {
  cell.indentationLevel = kIndentFDA
} else {
  cell.indentationLevel = kIndentCompleted
}

But when I write this:

indexPath.row == 0 ? cell.indentationLevel = kIndentFDA : cell.indentationLevel = kIndentCompleted

I get this compiler warning:

"Cannot assign to immutable expression of type 'Int'"

2

There are 2 answers

0
Craig Siemens On BEST ANSWER

I don't know what the warning it but it probably can't figure out the order to apply the operators. This should work.

cell.indentationLevel = indexPath.row == 0 ? kIndentFDA : kIndentCompleted

6
matt On

The problem is that you don't understand what the ternary operator is. It isn't for performing assignments within the branches; the branches are not executable statements. Rather, the branches are evaluated expressions; thus, you use the ternary operator in the rvalue of an assignment and the branch values themselves are what is assigned.

So, you are writing this (which is nonsense):

indexPath.row == 0 ? cell.indentationLevel = kIndentFDA : cell.indentationLevel = kIndentCompleted

What you mean is:

cell.indentationLevel = indexPath.row == 0 ? kIndentFDA : kIndentCompleted