swift - 在由 Swift 枚举确定的函数中使用一元运算符

标签 swift

想要使用枚举并根据枚举值,使用 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,它根据selfcase 返回二进制操作。

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/

相关文章:

xcode - 填充和编辑 NSView 内容

swift - 测试运行程序在完成运行测试之前退出并显示代码 9

swift - 如何防止 Swift 枚举的失败初始化程序在原始数字范围内返回 nil?

ios - Swift: UIImagePicker 可以自动打开上次拍摄的照片吗?

ios - 带有 ScrollView 的 ViewController 显示空屏幕

swift - 二元运算符不能应用于两个 'NSWindowStyleMask' 操作数

ios - 在 iOS 或 macOS 系统上复制所选文本后是否可以启动我的应用程序?

ios - UIDatePicker 作为倒数计时器 1 分钟不是 60 秒

swift - 某些 iOS 应用程序如何知道何时失去互联网连接

ios - Int64 不工作,而 Int 工作