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

2019-01-20 09:45发布

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.

2条回答
别忘想泡老子
2楼-- · 2019-01-20 10:29

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
查看更多
Bombasti
3楼-- · 2019-01-20 10:33

In the simplest case, you can replace ++column with column + 1:

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

You can also rewrite your code in an if-else statement with a += operator:

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

Moreover, although I would not recommend using it in production code, you can reimplement ++ (prefix / postfix increment operator) and -- (prefix / postfix decrement operator) for type Int in Swift 2.2 and Swift 3 with custom operators, in-out parameters and defer statement.

// Swift 2.2

prefix operator ++ {}
prefix operator -- {}
postfix operator ++ {}
postfix operator -- {}

prefix func ++(inout a: Int) -> Int {
    a += 1
    return a
}

prefix func --(inout a: Int) -> Int {
    a -= 1
    return a
}

postfix func ++(inout a: Int) -> Int {
    defer { a += 1 }
    return a
}

postfix func --(inout a: Int) -> Int {
    defer { a -= 1 }
    return a
}
// Swift 3

prefix operator ++
prefix operator --
postfix operator ++
postfix operator --

@discardableResult prefix func ++( a: inout Int) -> Int {
    a += 1
    return a
}

@discardableResult prefix func --( a: inout Int) -> Int {
    a -= 1
    return a
}

@discardableResult postfix func ++( a: inout Int) -> Int {
    defer { a += 1 }
    return a
}

@discardableResult postfix func --( a: inout Int) -> Int {
    defer { a -= 1 }
    return a
}

As an example, the following playground code that uses ternary operator generates no warnings with Swift 2.2 and Swift 3:

var a = 10
print(a++) // prints 10
print(a) // prints 11

var b = 10
print(--b) // prints 9
print(b) // prints 9

var column = 0
column = column >= 2 ? 0 : ++column
print(column) // prints 1
查看更多
登录 后发表回答