代码:
enum ArithmeticExpression { // 相关值 case Number(Int) // 递归枚举 indirect case Addition(ArithmeticExpression, ArithmeticExpression) indirect case Multiplication(ArithmeticExpression, ArithmeticExpression) indirect case Division(ArithmeticExpression, ArithmeticExpression) } func evaluate(expression: ArithmeticExpression) -> Int { switch expression { case .Number(let value): return value case .Addition(let left, let right): return evaluate(left) + evaluate(right) case .Multiplication(let left, let right): return evaluate(left) * evaluate(right) case .Division(let left, let right): return evaluate(left) / evaluate(right) } } let five = ArithmeticExpression.Number(5) let four = ArithmeticExpression.Number(4) let sum = ArithmeticExpression.Addition(five, four) let product = ArithmeticExpression.Multiplication(sum, ArithmeticExpression.Number(2)) let quotient = ArithmeticExpression.Division(five, four) print(evaluate(sum)) print(evaluate(product)) print(evaluate(quotient))
输出:
9 18 1