想要使用枚举并根据枚举值,使用 Swift (v3) 执行加法或减法。
这样我就可以避免类似的事情:
enum Direction {
case east, west
}
func example(direction:Direction, _ left: Int, _ right: Int) -> Int {
// ...
// next a bunch of functions that depending on the direction add or subtract two values
// would like to avoid the following repetitive evaluations:
let oneOfTheCalculations = direction == .east ? left + right : left - right
//let anotherCalculation = direction == .east ? left + 2*right : left - 2*right
//let andAnotherOne = direction == .east ? left + 3*right : left - 3*right
//...
return oneOfTheCalculations
}
print("\( example(direction:.east, 4, 3) )") // 7
print("\( example(direction:.west, 4, 3) )") // 1
我假设可以使运算符函数成为枚举的一部分,因此我不需要通过比较来确定要执行的操作。
也许按照例如:
func doit(_ myOperator:(Int,Int)->Int, _ left:Int, _ right:Int) -> Int {
return myOperator(left,right)
}
print("\( doit(+,4,3) )")
print("\( doit(-,4,3) )")
最佳答案
您可以向您添加一个方法enum
,它根据self
的case
返回二进制操作。
enum Direction {
case east, west
func combine<T: IntegerArithmetic>() -> (T, T) -> T {
switch self {
case .east: return (+)
case .west: return (-)
}
}
}
func example(direction: Direction, _ left: Int, _ right: Int) -> Int {
let oneOfTheCalculations = direction.combine()(left, right)
let anotherCalculation = direction.combine()(left, 2*right)
let andAnotherOne = direction.combine()(left, 3*right)
//...
return oneOfTheCalculations
}
或者,简单地让 enum
方法自己执行组合评估,只返回结果:
enum Direction {
case east, west
func combine<T: IntegerArithmetic>(_ lhs: T, _ rhs: T) -> T {
switch self {
case .east: return lhs + rhs
case .west: return lhs - rhs
}
}
}
func example(direction: Direction, _ left: Int, _ right: Int) -> Int {
let oneOfTheCalculations = direction.combine(left, right)
let anotherCalculation = direction.combine(left, 2*right)
let andAnotherOne = direction.combine(left, 3*right)
//...
return oneOfTheCalculations
}
关于swift - 在由 Swift 枚举确定的函数中使用一元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43659880/