码迷,mamicode.com
首页 > 编程语言 > 详细

Swift枚举-相关值与递归枚举

时间:2015-08-16 22:46:42      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

代码:

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

 

Swift枚举-相关值与递归枚举

标签:

原文地址:http://www.cnblogs.com/loftyspirit/p/4734981.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!