枚举的基本用法
// 定义枚举
enum Direction {
case north
case source
case east
case west
}
// 也可以写成
enum Direction {
case north, source, east, west
}
可以用于switch语句:
let dir: Direction = .north
switch 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 = 0
case right = 1
case up = 2
case down = 3
}
var dir = direction.left
print(dir) // left
print(dir.rawValue) // 0
隐式原始值(Implicitly Assigned Raw Values)
如果枚举的原始值是Int、String,Swift会自动分配原始值
enum Direction: Int {
case north
case source
case east
case west
}
print(Direction.north.rawValue, Direction.source.rawValue) // 0 1
enum Direction: String {
case north
case source
case east
case 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 // 8
MemoryLayout<Int>.stride // 8
MemoryLayout<Int>.alignment // 8
// 获取变量所占内存
var age = 10
MemoryLayout.size(ofValue: age) // 8
MemoryLayout.stride(ofValue: age) // 8
MemoryLayout.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.other
MemoryLayout<Password>.size // 33,实际用到的空间大小
MemoryLayout<Password>.stride // 40,分配战洪的空间大小
MemoryLayout<Password>.alignment // 8,对齐参数
enum Season: Int {
case spring, summer, autumn, winter
}
MemoryLayout<Season>.size // 1
MemoryLayout<Season>.stride // 1
MemoryLayout<Season>.alignment // 1
原始值不占用枚举变量的内存,占用内存的是spring.rawValue
let s = Season.spring
MemoryLayout.size(ofValue: s.rawValue) // 16
MemoryLayout.stride(ofValue: s.rawValue) // 16
MemoryLayout.alignment(ofValue: s.rawValue) // 8