美文网首页iOS Developer
Swift递归枚举的简单运用

Swift递归枚举的简单运用

作者: BBH_Life | 来源:发表于2017-04-26 15:26 被阅读78次

    Swift枚举中有一种特殊用法叫做递归枚举,在枚举中可以调用自己,这样可以很方便的来表达一些链式的表达式。例如表达数字计算式等等。下列是一个简单例子,使用递归枚举和递归函数来实现简单的表达式计算函数。

    import Foundation
    
    /*使用递归枚举表达加减乘除*/
    /*并使用函数计算结果*/
    indirect enum math {
        case num(Int)
        case plus(math,math)
        case sub(math,math)
        case multi(math,math)
        case divide(math,math)
    }
    
    /*
     表达(3+5)*20/5
     */
    
    let three = math.num(3)
    let five = math.num(5)
    let threePlusFive = math.plus(three, five)
    let multiTwenty = math.multi(threePlusFive, math.num(20))
    let divideFive = math.divide(multiTwenty, math.num(5))
    
    func calculate(expresion : math) -> Int {
        switch expresion {
        case let .num(value):
            return value
        case let .multi(first, seconde):
            return calculate(expresion: first) * calculate(expresion: seconde)
        case let .plus(first, seconde):
            return calculate(expresion: first) + calculate(expresion: seconde)
        case let .divide(first, seconde):
            return calculate(expresion: first) / calculate(expresion: seconde)
        default:
            return -1
        }
    }
    
    print(calculate(expresion: divideFive))
    

    相关文章

      网友评论

        本文标题:Swift递归枚举的简单运用

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