在掘金上看到从 汇编 到 Swift 枚举内存 的惊鸿一瞥以后,做者分析了几种不一样枚举的内存布局,可是我感受覆盖的不够全面,算是对做者那篇文章的一个补充。建议先看下做者的文章,做者的结论以下:git
关联值枚举: 最大字节数之和 额外 + 1 最后一个字节 存放 case 类型 非关联值枚举: 内存 占用 1个字节 内存中 如下标数 为值,依次累加github
不知道你看完以后,有没有我一样的疑问?bash
func test(){
enum TestEnum {
case testCase1
case testCase2
}
var testEnum = TestEnum.testCase1
show(val: &testEnum)
testEnum = .testCase2
show(val: &testEnum)
}
复制代码
//测试case过多时
func test1(){
var testEnum = MoreCaseEnum.case257
show(val: &testEnum)
}
复制代码
struct TestStruct: TestProtocol {
var testPropetry1 = 10
var testPropetry2 = 11
var testPropetry3 = 12
var testPropetry4 = 13
var testPropetry5 = 14
}
func test2() {
enum TestStructEnum {
case testCase1
case testCase2(TestStruct)
case testCase3
}
var testEnum = TestStructEnum.testCase1
show(val: &testEnum)
testEnum = .testCase2(TestStruct())
show(val: &testEnum)
testEnum = .testCase3
show(val: &testEnum)
}
复制代码
//测试关联值的类型是class
func test3() {
enum TestClassEnum {
case testCase1
case testCase2(TestClass)
case testCase3
}
var testEnum = TestClassEnum.testCase1
show(val: &testEnum)
testEnum = .testCase2(TestClass())
show(val: &testEnum)
testEnum = .testCase3
show(val: &testEnum)
}
复制代码
func test4() {
enum TestClassOtherEnum {
case testCase1
case testCase2(TestClass)
case testCase3(Bool)
}
var testEnum = TestClassOtherEnum.testCase1
show(val: &testEnum)
testEnum = .testCase2(TestClass())
show(val: &testEnum)
testEnum = .testCase3(true)
show(val: &testEnum)
}
复制代码
func test5() {
enum TestEnum {
case testCase1
case testCase2
}
enum TestSamllEnum {
case testCase1
case testCase2(TestEnum)
case testCase3(Bool)
}
var testEnum = TestSamllEnum.testCase1
show(val: &testEnum)
testEnum = .testCase2(.testCase2)
show(val: &testEnum)
testEnum = .testCase3(true)
show(val: &testEnum)
}
复制代码
func test6() {
enum TestProtocolEnum {
case testCase1
case testCase2(TestProtocol)
case testCase3
}
var testEnum = TestProtocolEnum.testCase1
show(val: &testEnum)
testEnum = .testCase2(TestClass())
show(val: &testEnum)
testEnum = .testCase2(TestStruct())
show(val: &testEnum)
testEnum = .testCase3
show(val: &testEnum)
}
复制代码
func test7() {
indirect enum TestIndirectEnum {
case testCase1
case testCase2(TestIndirectEnum)
case testCase3
}
var testEnum = TestIndirectEnum.testCase1
show(val: &testEnum)
testEnum = .testCase2(.testCase3)
show(val: &testEnum)
testEnum = .testCase3
show(val: &testEnum)
}
复制代码
以上全部的结论都是测试并总结出来,不能保证绝对的正确性,仅供参考,测试demo函数
Memspost