swift递归枚举

Posted by 海纳百川 on Thursday, February 22, 2024

递归枚举

递归枚举是一种枚举类型 有一个或多个枚举成员使用该枚举类型的作为枚举成员 在枚举成员前加上 indirect 来表示该成员可递归

enum ArithmeticExpression {
    case number(Int)
    indirect case addition(ArithmeticExpression, ArithmeticExpression)
    indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
}

应用

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(value1, value2):
        return evaluate(value1) + evaluate(value2)
    case let .multiplication(value1, value2):
        return evaluate(value1) - evaluate(value2)
    }
}
let num = ArithmeticExpression.number(5)
print(evaluate(num))    // 打印 "5"
print(evaluate(ArithmeticExpression.addition(num, num)))    // 打印 "10"
print(evaluate(ArithmeticExpression.multiplication(num, num)))    // 打印 "0"