Swift开篇006->枚举

来源:互联网 发布:现货数据行情分析系统 编辑:程序博客网 时间:2024/06/07 03:57

PART_A 枚举简介

  1. 定义:一组相关的值定义了一个共同的枚举类型

  2. 语法格式

    enum Direction {    case East    case South    case West    case North    case NorthWest, EastSouth // 多个成员值在一行时,可用逗号分开}
  3. 类型推断

    var currentDirection = Direction.East // 当类型已被推断出,可用简短语句(省略枚举类型名)来设置值:._currentDirection =.South
  4. 使用Switch匹配枚举值

    • switch需要穷举枚举成员,可以使用default分支来涵盖所有未明确处理的枚举成员

      var currentDirection = Direction.East               switch currentDirection {    case .East:        print("East")    case .South:        print("South")    case .West:        print("West")    case .North:        print("North")    case .NorthWest, .EastSouth:        print("Other")    default:        print("Default")    }

PART_B 关联值

  1. 定义:将枚举成员使用元组组合成关联值

  2. 注意:同一变量可被分配成不同类型的关联值,但同一时刻仅能存储为一种类型

  3. 语法格式

    enum Person {    case Male(String, Int)    case Female(String, String)}func test() {    var p1 = Person.Male("zhangsan", 28)    switch p1 {    case .Male(let name, let age):        print("\(name), \(age)")    // 元组成员类型相同时,可提出类型至case后面    case let .Female(name, desc):         print("\(name), \(desc)")    }}

PART_C1 原始值:原始值的类型必须相同

  1. 定义:即默认值. 对于一个特定的枚举成员,其原始值始终不变

  2. 说明

    • 原始值类型可为字符、字符串、任意整型值、任意浮点型值

    • 每个原始值在枚举声明中必须是唯一的

    • 系统提供方法获取原始值:rawValue

  3. 语法格式

    enum OriginStr: String {    case str1 = "hi"    case str2 = "how are you"}

PART_C2 原始值的隐式赋值

  1. 当使用整数作为原始值,隐式赋值依次递增1. 若第一个枚举成员未设置原始值,默认为0

  2. 当使用字符串作为原始值,每个枚举成员的隐式原始值为该枚举成员的名称

    // 枚举类型一、星球(整型)enum Planet: Int {    case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune}// 枚举类型二、方位(字符串)enum CompassPoint: String {    case North, South, East, West}// 使用 rawValue 取默认原始值let earthsOrder = Planet.Earth.rawValue // earthOrder 值为 3
  3. 使用原始值初始化枚举实例

    let possiblePlanet = Planet(rawValue: 7)// possiblePlanet类型为可选值:Planet?// 越界将返回 nil,否则将对应星球赋值给 possiblePlanet

PART_D 递归枚举(indirect):情况可被穷举时,适合数据建模

以下为解决案例:(3 + 4) * 5

  1. 定义

    • 方式一

      enum ArithmeticExpression {    case Num(Int)    indirect case Add(ArithmeticExpression, ArithmeticExpression)    indirect case Multiple(ArithmeticExpression, ArithmeticExpression)}
    • 方式二:所有成员可递归时,将 indirect 放在 enum 声明前

      indirect enum ArithmeticExpression2 {    case Num(Int)    case Add(ArithmeticExpression, ArithmeticExpression)    case Multiple(ArithmeticExpression, ArithmeticExpression)}
      // 定义运算方法func test(expression: ArithmeticExpression) -> Int {    switch expression {    case let .Num(value):        return value    case let .Add(a, b):        return test11(a) + test11(b)    case let .Multiple(a, b):        return test11(a) * test11(b)    }}
      // 调用运算方法、递归枚举进行运算let three = ArithmeticExpression.Num(3)let four = ArithmeticExpression.Num(4)let sum = ArithmeticExpression.Add(three, four)let result = ArithmeticExpression.Multiple(sum, ArithmeticExpression.Num(5))// result 值为 35

以上。如有错误和疑问,欢迎指正提出。 catface.wyh@gmail.com

0 0
原创粉丝点击