Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rewrite Swift ++ operator in ?: ternary operator

Tags:

swift

swift2.2

I have the following code

var column = 0

column = column >= 2 ? 0 : ++column

Since 2.2 I get a depreciation warning, any ideas how I can fix this?

I have this solution:

if column >= 2 {
    column = 0
} else {
    column += 1
}

But this isn't really nice.

like image 833
patrickS Avatar asked Mar 23 '16 13:03

patrickS


People also ask

Does Swift have a ternary operator?

Swift has a rarely used operator called the ternary operator. It works with three values at once, which is where its name comes from: it checks a condition specified in the first value, and if it's true returns the second value, but if it's false returns the third value.

What does ~= mean in Swift?

The expression represented by the expression pattern is compared with the value of an input expression using the Swift standard library ~= operator. The matches succeeds if the ~= operator returns true . By default, the ~= operator compares two values of the same type using the == operator.


1 Answers

How about:

column = (column >= 2) ? 0 : column+1

It looks like you might be doing something like clock arithmetic. If so, this gets the point across better:

column = (column + 1) % 2
like image 195
Lou Franco Avatar answered Sep 28 '22 05:09

Lou Franco