gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:44:09 24 4
gpt4 key购买 nike

我创建了一个枚举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)

最佳答案

我建议为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
}
}

关于swift - 如何使用枚举创建计算函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56152777/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com