作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我创建了一个枚举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/
我是一名优秀的程序员,十分优秀!