枚举的基本用法
在C,OC中,枚举就是整形,0,1,2,3...
在swift中的基本用法

关联值(Associated Value)
什么时候用枚举,要表达的东西只有几个固定
的值

第一个score的例子,是将96这个整型和A这个字符型都存储在枚举的内存中的
第二个Date的例子中三个整型year month day和string类型的2011-09-10也是存储在枚举的内存中
关联值的意思是将不同类型的值一起存储到枚举的内存中
关联值应用举例:

// 原始值(Raw Vlaues)
enum pukeCard: Character {
case red = "♥️"
case black = "♠️"
case diamond = "♦️"
case meihua = "♣️"
}
// 将pukeCard的第一个成员red赋值给变量suit
var suit = pukeCard.red
print(suit)// 打印出来就是成员的名字
print(suit.rawValue)// 打印出来就是成员的关联值
print(pukeCard.diamond.rawValue)// 打印出来也是原始值
// 冒号后面代表原始值是什么类型
enum Grade: String {
case perfect = "A"
case great = "B"
case good = "C"
case bad = "D"
}
print(Grade.perfect.rawValue)
print(Grade.great.rawValue)
print(Grade.good.rawValue)
print(Grade.bad.rawValue)
隐式原始值

递归枚举(Recursive Enumeration)

关联值的内存布局
var age = 10 // 此时age是int类型
// 定义一个枚举有两个成员,其中number有关联值
// 一般枚举名称首字母大写,遵循驼峰规则,成员一般小写
enum Password {
case number(Int,Int,Int,Int)
case other
}
// 在oc中使用sizeof获取内存大小
MemoryLayout<Int>.size// 8 实际所占的内存空间大小
MemoryLayout<Int>.stride// 8 分配所占的内存空间大小
MemoryLayout<Int>.alignment// 8 内存对齐
MemoryLayout<Password>.size// 33 实际所占的内存空间大小(其中关联值占用4*8 = 32 other只需要占用1)
MemoryLayout<Password>.stride// 40 分配所占的内存空间大小 因为要内存对齐所以只能是8的倍数
MemoryLayout<Password>.alignment// 8 内存对齐
var pwd = Password.number(5, 6, 7, 8)
pwd = Password.other// 注意变量一旦分配了内存,是不会随着赋值的改变,内存大小就改变了,一开始分配了多大就是多大
MemoryLayout.size(ofValue: pwd)// 33 实际所占的内存空间大小(其中关联值占用4*8 = 32 other只需要占用1)
MemoryLayout.stride(ofValue: pwd)// 40 分配所占的内存空间大小 因为要内存对齐所以只能是8的倍数
MemoryLayout.alignment(ofValue: pwd)// 8 内存对齐
下面看原始值,神奇的事情发生了
,竟然只占一个
enum Season {
case spring,summer,atumum,winter
}
MemoryLayout<Season>.size// 1
MemoryLayout<Season>.stride// 1
MemoryLayout<Season>.alignment// 1
// 这样写依然是只占一个字节
enum Season: Int {
case spring = 1,summer,atumum,winter
}
MemoryLayout<Season>.size// 1
MemoryLayout<Season>.stride// 1
MemoryLayout<Season>.alignment// 1
重点在于关联值和原始值的区别
关联值里的成员允许被改变,而原始值里的值是不允许被改变的
关联值的内存受number()里面关联值类型的影响,并随之改变
原始值的默认值一成不变没必要为此去浪费内存存储,哪怕Season: String(string占用16个字节),但他依然只占用1个字节.
enum Season: String {
case spring = "1",summer = "2",atumum = "3",winter = "4"
}
MemoryLayout<Season>.size// 1
MemoryLayout<Season>.stride// 1
MemoryLayout<Season>.alignment// 1
var s = Season.spring
MemoryLayout.size(ofValue: s)// 1
MemoryLayout.stride(ofValue: s)// 1
MemoryLayout.alignment(ofValue: s)// 1

在一个枚举后面
enum Season: Int
或enum Season: String
这种被称为原始值,而关联值后面则没有明确类型如果枚举是关联值,可以传入具体值进行关联的,到时候传入的关联值是直接存储到枚举变量pwd(上述代码中)的内存中的
如果枚举是关联值,原始值默认是和成员绑定的,到时候是不会占用枚举变量s(上述代码中)的内存的
网友评论