递归枚举是指枚举类型中的一个或多个case关联到同一枚举类型。递归枚举在定义时需要使用 indirect 关键字来标记关联的case。
indirect enum ArithmeticExpression {
case number(Int)
case addition(ArithmeticExpression, ArithmeticExpression)
case multiplication(ArithmeticExpression, ArithmeticExpression)
}
func evaluate(_ expression: ArithmeticExpression) -> Int { switch expression {
case let .number(value):
return value
case let .addition(left, right):
return evaluate(left) + evaluate(right)
case let .multiplication(left, right):
return evaluate(left) * evaluate(right) }
}
let expression = ArithmeticExpression.addition(.multiplication(.number( 2), .number(3)), .number(5))
let result = evaluate(expression) // 结果为11