枚举的基本用法
// 定义枚举enum Direction {case northcase sourcecase eastcase west}// 也可以写成enum Direction {case north, source, east, west}
可以用于switch语句:
let dir: Direction = .northswitch dir {case .north:print("north")case .source:print("north")case .east:print("north")case .west:print("north")}
关联值(Associated Valuse)
有时会将枚举的成员值跟其他类型关联存储在一起,会非常有用
// 分数举例enum Score {case point(Int)case grade(Character)}var s = Score.point(96)s = .grade("A")
// 日期举例enum Date {case digit(year: Int, month: Int, day: Int)case string(String)}var date = Date.digit(year: 2018, month: 8, day: 8)date = .string("2018-8-8")switch date {case .digit(let year, let month, let day):print(year, month, day)case let .string(value):print(value)}
原始值(Raw Values)
枚举成员可以使用相同类型的默认值预先关联,这个默认值叫做:原始值
enum direction: Int {case left = 0case right = 1case up = 2case down = 3}var dir = direction.leftprint(dir) // leftprint(dir.rawValue) // 0
隐式原始值(Implicitly Assigned Raw Values)
如果枚举的原始值是Int、String,Swift会自动分配原始值
enum Direction: Int {case northcase sourcecase eastcase west}print(Direction.north.rawValue, Direction.source.rawValue) // 0 1
enum Direction: String {case northcase sourcecase eastcase west}print(Direction.north.rawValue, Direction.source.rawValue) // north source
递归枚举
需要使用indirect关键字
indirect enum ArithExpr {case number(Int)case sum(ArithExpr, ArithExpr)case diffrence(ArithExpr, ArithExpr)}let five = ArithExpr.number(5)let four = ArithExpr.number(4)let sum = ArithExpr.sum(five, four)let diffrence = ArithExpr.diffrence(sum, four)
MemoryLayout
可以使用MemoryLayout获取数据类型所占内存大小
// 获取类型所占内存MemoryLayout<Int>.size // 8MemoryLayout<Int>.stride // 8MemoryLayout<Int>.alignment // 8// 获取变量所占内存var age = 10MemoryLayout.size(ofValue: age) // 8MemoryLayout.stride(ofValue: age) // 8MemoryLayout.alignment(ofValue: age) // 8
获取枚举所占内存大小
/// 带有关联值的枚举enum Password {case number(Int, Int, Int, Int)case other}let number = Password.number(1, 2, 3, 4)let other = Password.otherMemoryLayout<Password>.size // 33,实际用到的空间大小MemoryLayout<Password>.stride // 40,分配战洪的空间大小MemoryLayout<Password>.alignment // 8,对齐参数
enum Season: Int {case spring, summer, autumn, winter}MemoryLayout<Season>.size // 1MemoryLayout<Season>.stride // 1MemoryLayout<Season>.alignment // 1
原始值不占用枚举变量的内存,占用内存的是spring.rawValue
let s = Season.springMemoryLayout.size(ofValue: s.rawValue) // 16MemoryLayout.stride(ofValue: s.rawValue) // 16MemoryLayout.alignment(ofValue: s.rawValue) // 8
