7

I've been updating my Swift code for Swift 3 (really excited) and so far so good. But I did tumble accros one little bit of code I can't seem to update.

I KNOW I am missing something very simple, but I just can't see what.

Here is what I have in Swift 2.2:

var column = 0

[...]

for item in 0 ..< collectionView!.numberOfItemsInSection(0) {
    [...]

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

The ++column is of course being deprecated in Swift 3 in favor of column += 1

However, in THIS context, it produces an error:

No '+=' candidates produce the expected contextual result type 'Int'

Since this line of code (column = column >= (numberOfColumns - 1) ? 0 : column += 1) produces an error, I tried the following:

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

But I get the same error.

Could someone point me in the correct direction?

0

2 Answers 2

9

+= does not return a value. You need to break this out. Luckily in your case that's straightforward and clearer than the original:

column = (column + 1) % numberOfColumns
7

Like this:

column = column >= (numberOfColumns - 1) ? 0 : column + 1
3
  • 2
    It answers the OP's question most clearly and directly but as usual Rob Napier's answer is the elegant Swifty way. :)
    – matt
    Mar 31, 2016 at 17:00
  • yeah, what can ya do?
    – GetSwifty
    Mar 31, 2016 at 17:03
  • I tried this out, but it just adds 1 instead of += 1. .map { _ in NSIndexPath(forRow: insertPos++, inSection: 0) } In my case, the n + 1 doesn't work
    – Trip
    Apr 21, 2016 at 19:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.