问题
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