Swift递归枚举的简单运用

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))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本章将会介绍 闭包表达式尾随闭包值捕获闭包是引用类型逃逸闭包自动闭包枚举语法使用Switch语句匹配枚举值关联值原...
    寒桥阅读 5,438评论 0 3
  • 转载自:https://github.com/Tim9Liu9/TimLiu-iOS[https://github...
    香橙柚子阅读 12,827评论 0 36
  • 学车的日子也不短了,练车的感觉也一时一时的,但近来我很充实,更多的是满足。 再就是想要说说我的教练们,年龄都比我小...
    恋峦无言阅读 1,215评论 0 0
  • 一个人的豁达,体现在落魄的时候。 一个人的涵养,体现在愤怒的时候。 一个人的体贴,体现在悲伤的时候。 一个人的成熟...
    天使思雅阅读 1,215评论 0 0
  • 9月8日(补):今天和天夏一起阅读了一则寓言:《徒劳的寒鸦》。每则故事都是我先读两遍给她听,让她慢慢有了一些初步的...
    伴天夏成长阅读 1,521评论 0 0