美文网首页
Swift 5.x 递归 enum

Swift 5.x 递归 enum

作者: ShenYj | 来源:发表于2020-06-30 22:50 被阅读0次
    • 递归枚举是拥有另一个枚举作为枚举成员关联值的枚举.
      当编译器操作递归枚举时必须插入间接寻址层.
      你可以在声明枚举成员之前使用indirect关键字来明确它是递归的.

    e.g. 表达式(5+4)*2

    indirect enum ArithmeticExpression {
        case number(Int)
        case addition(ArithmeticExpression, ArithmeticExpression)
        case multiplication(ArithmeticExpression, ArithmeticExpression)
    }
    
    let five = ArithmeticExpression.number(5)
    let four = ArithmeticExpression.number(4)
    let sum = ArithmeticExpression.addition(five, four)
    let multiplyExpression = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))
    
    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)
        }
    }
    print(evaluate(multiplyExpression))
    

    输出结果:

    18
    

    Switch值绑定处的另一种写法

    indirect enum ArithmeticExpression {
        case number(Int)
        case addition(ArithmeticExpression, ArithmeticExpression)
        case multiplication(ArithmeticExpression, ArithmeticExpression)
    }
    
    let five = ArithmeticExpression.number(5)
    let four = ArithmeticExpression.number(4)
    let sum = ArithmeticExpression.addition(five, four)
    let multiplyExpression = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))
    
    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)
        }
    }
    print(evaluate(multiplyExpression))
    

    相关文章

      网友评论

          本文标题:Swift 5.x 递归 enum

          本文链接:https://www.haomeiwen.com/subject/utifqktx.html