在掘金上看到從 彙編 到 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