iOS Swift 学习手册 程序员

Swift学习(七:枚举)

2016-07-22  本文已影响21人  爱偷懒的万万
1.枚举语法
    enum Some{
            //枚举定义
    }

    enum Someone{
            case north
            case south
            case east
            case west
    }

多个成员值可以出现在同一行上,用逗号隔开

    enum Some{
            case north,south,east,west
    }
    每一个枚举定义了一哥全新的类型:
    var aa = Some.east
    简写: var aa = .east
2.使用Switch语句匹配枚举
    aa = .east
    switch aa{
            case .north:
                   print()
             case .south:
                   print()
             case .east:
                   print()
             case .west:
                   print()
     }
3.关联值

在定义枚举的时候,可以为该成员变设置关联值

    enum some{
            case aa(Int,Int,Int,Int)
            case bb(String)
    }
    调用:var cc = some.aa(1,2,3,4)
    或者简写: var cc = .aa(1,2,3,4)

关联值可以被提取出来作为 switch 语句的一部分。你可以在switch
的 case 分支代码中提取每个关联值作为一个常量(用let
前缀)或者作为一个变量(用var前缀)来使用:

    switch cc{
            case aa(let a,let b,let c,let d):
                      print(a,b,c,d)
            case bb(let str)
                       print(str)
    }

如果一个枚举成员的所有关联值都被提取为常量,或者都被提取为变量,为了简洁,你可以只在成员名称前标注一个let
或者var

    switch cc{
            case let aa( a, b,c, d):
                      print(a,b,c,d)
            case let bb( str)
                       print(str)
    }
4.原始值

注意,并不是左右的值都可以找到匹配的枚举成员 ,因此原始值构造器总是返回一个可选的枚举成员,
原始值构造器是一个可失败构造器,因为并不是每一个原始值都有与之对应的原始值,如果没有,则为nil

5.递归枚举

是一种枚举类型,有一个或多个枚举成员使用该枚举类型的实例作为关联值。使用递归枚举,编译器会插入一个中间层,可以在枚举成员前加上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)
      }

调用:

 let five = ArithmeticExpression.Number(5)
 let four = ArithmeticExpression.Number(4)
 let sum = ArithmeticExpression.Addition(five, four)
 let product = 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(product))
      // 输出 "18"
上一篇 下一篇

猜你喜欢

热点阅读