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

荒凉一梦 提交于 2019-11-27 07:49:36

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/36178975/how-to-rewrite-swift-operator-in-ternary-operator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!