Swift-枚举

1. 枚举的写法

/**
*   方式1:每个成员前面用case 并 换行
*/
enum Season {
  case spring
  case summer
  case autumn
  case winter
}

/**
*   方式2:只用一个case,成员之间用逗号隔开
*/
enum Season {
  case spring, summer, autumn, winter
}

注意

枚举成员建议用小写字母开头

2. 原始值

使用同种类型的默认值关联,此默认值成为原始值

/**
*   例子1 Int类型,后面的成员值会递增
*/
enum Season: Int {
  case spring = 1
  case summer
  case autumn = 4
  case winter
}
print(Season.spring.rawValue, Season.winter.rawValue)
// 结果:1 5

/**
*   例子 2 Float类型
*/
enum Level: Float {
  case low = 1.0
  case mid
  case high
}
print(Level.low.rawValue, Level.high.rawValue)
// 结果:1.0 3.0

使用Int、String 时,系统会默认分配给枚举成员对应的默认值

enum Direction: String {
  case north        // 默认分配north
  case south
  case east
  case west
}
print(Direction.north.rawValue)
// 结果:north

注意

  1. 原始值必须要明确写出清枚举成员的类型。如Int、String。否则无法使用rawValue属性

  2. Character类型暂时无法使用

3. 关联值

将成员值与其他类型值关联一起,这种关联信息成为关联。

enum Date {
  case date(year:Int, month:Int, day:Int)   // 关联Int类型
  case dateStr(String)          // String类型
}
let date = Date.date(year:2019, month:9, day:7)
print(date)
// 结果:date(year:2019, month:9, day:7)
/**
*   例子:利用switch进行区分
*/
enum gradeScore {
  case point(Float)
  case grade(String)
}

let score = Score.point(97.5)
switch score {
  case let .point(x)
    print("point is \(x)")
  case let .grade(y):
    print ("grade is \(y)")
}
print(score)
// 结果:point is 97.5

4. 递归枚举

枚举成员类型为枚举类型本身。使用时需要在前面添加 indirect

indirect enum Algrth {
  case num(Int)
  case sum(Algrth, Algrth)
  case diff(Algrth, Algrth)
}

let num1 = Algrth.num(7)
let num2 = Algrth.num(8)
let sum = Algrth.sum(num1, num2)
let diff = Algrth.diff(num1, num2)

func calculate(_ algrth:Algrth) -> Int {
  switch algrth {
    case let .num(x):
        return x
    case let .sum(x, y)
        return calculate(x) + calculate(y)
    case let .diff(x, y)
        return calculete(x) - calculate(y)
  }
}

print(calculate(num1), calculate(num2), calculate(sum), calculate(diff))
// 结果:7,8,15,-1

5. 原始值 VS 关联值

  1. 内存分配情况

枚举变量并不存储原始值,大小为1字节。所以即使枚举成员类型是Int(16个字节) 或者 String(8个字节)都不影响,实际上只存储一个标志。

枚举变量各自存储关联值,大小为关联值成员大小的综合。

6. MemoryLayout

查看内存情况

enum Password {
  case number(Int, Int, Int, Int)   // 32
  case other            // 1
}

/**
*   写法1:查看类型的内存情况
*/
MemoryLayout.size     // 33 实际使用的内存大小
MemoryLayout.stride   // 40 系统分配的内存大小
MemoryLayout.alignment    // 8 内存对齐参数

/**
*   写法2:查看变量的内存情况
*/
let pwd = Password.number(9, 8, 7, 6)
MemoryLayout.size(ofValue: pwd)     // 33 实际使用的内存大小
MemoryLayout.stride(ofValue: pwd)   // 40 系统分配的内存大小
MemoryLayout.alignment(ofValue: pwd)    // 8 内存对齐参数
// 分析 Password 的内存
enum Password {
  case number(Int, Int, Int, Int)   // 32
  case other            // 1
}
let pwd = Password.number(9, 8, 7, 6)   // 33

/**
*   枚举变量各自存储关联值大小,因此是32 + 1 = 33
*   前面32个字节存储关联值,后1个字节存储枚举成员
*/

枚举变量的大小为1个字节存储成员值(用于区分成员)+ N个字节存储关联值(N取占用最大内存的关联值),任何一个case的关联值都共用这N个字节

你可能感兴趣的:(Swift-枚举)