-2

Swift 2 - Working Fine:

column = column >= (numberOfColumns - 1) ? 0 : ++column

Swift 3 - Error ('++' is unavailable: it has been removed in Swift 3):

column = column >= (numberOfColumns - 1) ? 0 : ++column

or try this one - Error ( Left side of mutating operator has immutable type 'Int'):

column = column >= (numberOfColumns - 1) ? 0 : column  += 1
rmaddy
  • 314,917
  • 42
  • 532
  • 579

1 Answers1

0

Generally

aVar = cond ? expr1 : expr2

is equivalent to:

if cond {
    aVar = expr1
} else {
    aVar = expr2
}

So, your ternary operator code is equivalent to this:

if column >= (numberOfColumns - 1) {
    column = 0
} else {
    column += 1 //<- ++column
    column = column //<- assigning the result of (++column) to column !!!!!!
}

But I think the same result can be assigned to column with this in most cases:

column = (column + 1) % numberOfColumns
OOPer
  • 47,149
  • 6
  • 107
  • 142
  • More correctly, the equivalent of the OP's code causing an issue is actually `column = column += 1` which is why it causes an error. Split as two lines as shown in this answer actually works and gives the desired result. – rmaddy Aug 11 '17 at 06:42
  • @rmaddy, My two lines in `else` part is illustrating how `column = ++column` is doing. Is there any thing wrong? – OOPer Aug 11 '17 at 06:45
  • My comment was based on the 3rd line of code in the question, not the second. – rmaddy Aug 11 '17 at 06:47
  • @rmaddy, I see, I should have shown which ternary operator my code is based on. But, anyway, new link shown is well describing the almost similar case and I think I do not need to update. – OOPer Aug 11 '17 at 06:49
  • 1
    Yeah, I deleted my answer due to the new duplicate. You may want to do the same since the answers for the duplicate show your same solution of using the modulus operator. – rmaddy Aug 11 '17 at 06:50
  • @rmaddy, I usually keep my posts and comments even if it shows my mistakes or faults, unless it's harmful. – OOPer Aug 11 '17 at 06:52