如何使用枚举创建计算函数?

时间:2019-05-15 15:20:14

标签: swift enumeration

我创建了一个枚举CalculationType并具有属性。 但是我认为我的代码应该看起来更短))

我想减少打印数量。


enum CalculationType: Int {
    case addition
    case subtraction
    case multiplication
    case division
}

func calculator(numberOne: Int, numberTwo: Int,_ calculationType: CalculationType) -> Int {
    var result = 0
    switch calculationType {
    case .addition: result = numberOne + numberTwo
    print("Result \(CalculationType.addition): \(numberOne) and \(numberTwo) equels \(result)")
    case .subtraction: result = numberOne - numberTwo
        print("Result \(CalculationType.subtraction): \(numberOne) and \(numberTwo) equels \(result)")
    case .multiplication: result = numberOne * numberTwo
        print("Result \(CalculationType.multiplication): \(numberOne) and \(numberTwo) equels \(result)")
    case .division: result = numberOne / numberTwo
        print("Result \(CalculationType.division): \(numberOne) and \(numberTwo) equels \(result)")
    }
    return result
}

calculator(numberOne: 5, numberTwo: 7, .addition)
calculator(numberOne: 5, numberTwo: 7, .subtraction)
calculator(numberOne: 5, numberTwo: 7, .multiplication)
calculator(numberOne: 5, numberTwo: 7, .division)

1 个答案:

答案 0 :(得分:0)

我建议给CalculationType一种执行计算的方法:

enum CalculationType {
    case addition
    case subtraction
    case multiplication
    case division
}

extension CalculationType {
    func perform<T: BinaryInteger>(_ lhs: T, _ rhs: T) -> T {
        switch self {
        case .addition:       return lhs + rhs
        case .subtraction:    return lhs - rhs
        case .multiplication: return lhs * rhs
        case .division:       return lhs / rhs
        }
    }
}

然后您可以像这样使用它:

func calculator(numberOne: Int, numberTwo: Int,_ calculationType: CalculationType) -> Int {
    return calculationType.perform(numberOne, numberTwo)
}

要处理被零除,可以在调用perform之前让调用者检查分母是否为零,或者可以定义perform来引发错误:

enum CalculationType {
    case addition
    case subtraction
    case multiplication
    case division
}

enum CalculationError: Error {
    case divideByZero
}

extension CalculationType {
    func perform<T: BinaryInteger>(_ lhs: T, _ rhs: T) throws -> T {
        switch self {
        case .addition:
            return lhs + rhs

        case .subtraction:
            return lhs - rhs

        case .multiplication:
            return lhs * rhs

        case .division:
            if rhs == 0 { throw CalculationError.divideByZero }
            return lhs / rhs
        }
    }
}

然后呼叫者可以检查错误:

func calculator(numberOne: Int, numberTwo: Int,_ calculationType: CalculationType) -> Int? {
    do {
        return try calculationType.perform(numberOne, numberTwo)
    } catch CalculationError.divideByZero {
        print("Whoops, divide by zero")
        return nil
    } catch {
        print("Some other error:", error)
        return nil
    }
}