1.枚举的基本用法
定义
enum Direction {
case north
case south
case east
case west
}
enum Direction {
case north, south, east, west
}
使用
var dir = Direction.west
dir = Direction.east
dir = .north
print(dir) // north
switch dir {
case .north:
print("north")
case .south:
print("south")
case .east:
print("east")
case .west:
print("west")
}
2.关联值(Associated Values)
有时将枚举的成员值跟其他类型的值关联存储在一起
enum Score {
case points(Int)
case grade(Character)
}
var score = Score.points(96)
score = .grade("A")
3.原始值(Raw Values)
枚举成员可以使用相同类型的默认值预先对应,这个默认值叫做:原始值
注意:原始值不占用枚举变量的内存
enum PokerSuit : Character {
♠" case spade = "
♥" case heart = "
♦" case diamond = "
♣" case club = "
}
var suit = PokerSuit.spade
print(suit) // spade
print(suit.rawValue) // ♠
print(PokerSuit.club.rawValue) // ♣
4.隐式原始值(Implicitly Assigned Raw Values)
如果枚举的原始值类型是Int、String,Swift会自动分配原始值
字符串的原始值默认和字符串相同
enum Direction : String {
case north = "north"
case south = "south"
case east = "east"
case west = "west"
}
// 等价于
enum Direction : String {
case north, south, east, west
}
整型默认从0开始递增
enum Season : Int {
case spring = 1, summer, autumn = 4, winter
}
print(Season.spring.rawValue) // 1
print(Season.summer.rawValue) // 2
print(Season.autumn.rawValue) // 4
print(Season.winter.rawValue) // 5
5.MemoryLayout
可以使用MemoryLayout获取数据类型占用的内存大小
enum Password {
case number(Int, Int, Int, Int)
case other
}
MemoryLayout<Password>.stride // 40, 分配占用的空间大小
MemoryLayout<Password>.size // 33, 实际用到的空间大小
MemoryLayout<Password>.alignment // 8, 对齐参数
var pwd = Password.number(9, 8, 6, 4)
pwd = .other
MemoryLayout.stride(ofValue: pwd) // 40
MemoryLayout.size(ofValue: pwd) // 33
MemoryLayout.alignment(ofValue: pwd) // 8