枚举
- 关联值: 枚举的成员值和其他类型的值关联储存,存储在枚举变量中
enum Date {
case digit(year: Int, month: Int, day: Int)
case string(String)
}
var date = Date.digit(year: 2019, month: 12, day: 31)
date = .string("2019-12-12")
switch date {
case .digit(let year, let month, var day):
day = 10
print(year, month, day)
case let .string(value):
print(value)
}
- 原始值: 枚举成员使用相同的默认值预先对应,这个默认值是原始值。原始值没有存储在枚举变量中
enum Grade: String {
case perfect = "A"
case great = "B"
case good = "C"
}
var grade = Grade.good
print(grade)
print(grade.rawValue)
print(Grade.perfect.rawValue)
//隐式原始值: 如果枚举的原始值类型是Int、String,Swift 会自动分配原始值。(Int: 从0开始按顺序给枚举成员原始值。String: 与枚举成员同名的原始值)
- 递归枚举
indirect enum ArithExper {
case num(Int)
case sum(ArithExper, ArithExper)
case dif(ArithExper, ArithExper)
}
enum ArithExper1 {
case num(Int)
indirect case sum(ArithExper, ArithExper)
indirect case dif(ArithExper, ArithExper)
}
let zore = ArithExper.num(0)
let two = ArithExper.num(2)
let sum = ArithExper.sum(zore, two)
func calculate(_ expr: ArithExper) -> Int {
switch expr {
case let .num(value):
return value
case let .sum(left, right):
return calculate(left) + calculate(right)
case let .dif(left, right):
return calculate(left) - calculate(right)
}
}
print(calculate(sum))
枚举变量内存布局
https://github.com/CoderMJLee/Mems 查看内存地址工具
小端:高高低低 内存地址高的放到高字节,内存地址低的放到低字节
- 1个字节存储成员值
- N个字节存储关联值(N取占用内存最大的关联值),任何一个case的关联值都共用这N个字节,默认值不占用枚举变量内存
enum TestEnum {
case test1(Int, Int, Int)
case test2(Int, Int)
case test3(Int)
case test4(Bool)
case test5
}
var e = TestEnum.test1(1, 2, 3)
// 01 00 00 00 00 00 00 00
// 02 00 00 00 00 00 00 00
// 03 00 00 00 00 00 00 00
// 00
// 00 00 00 00 00 00 00
e = .test4(true)
// 01 00 00 00 00 00 00 00
// 00 00 00 00 00 00 00 00
// 00 00 00 00 00 00 00 00
// 03
// 00 00 00 00 00 00 00