Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

53: swift中枚举的内存布局 #57

Open
platojobs opened this issue Oct 21, 2021 · 0 comments
Open

53: swift中枚举的内存布局 #57

platojobs opened this issue Oct 21, 2021 · 0 comments
Assignees
Labels
MobileDevelopment iOS、安卓、Flutter Technology technology
Projects

Comments

@platojobs
Copy link
Owner

enum TestEnum {
    case test0(Int , Int , Int)
    case test1(Int , Int)
    case test2(Int)
    case test3(Bool)
    case test4
}

print(MemoryLayout<TestEnum>.size) //25 实际用到的内存
print(MemoryLayout<TestEnum>.stride) //32个字节 申请分配的内存
print(MemoryLayout<TestEnum>.alignment) //8 内存对齐参数

// 一共申请32个字节,实际用到25个字节,实际要用到的内存要按关联值占用到的最大的内存,在本例中是test0最大,关联3个Int类型,在64位系统中每个Int占用8个字节
// 因此要用24个字节,另外要一个字节即第25个字节用来标识枚举成员值,后面的7个字节用来内存补齐,以满足内存对齐

// 小端模式
// 01 00 00 00 00 00 00 00
// 02 00 00 00 00 00 00 00
// 03 00 00 00 00 00 00 00
// 00 (这一个字节标识枚举的成员值,0代表test0)
// 00 00 00 00 00 00 00
var t = TestEnum.test0(1, 2, 3)
// 小端模式
// 04 00 00 00 00 00 00 00
// 04 00 00 00 00 00 00 00
// 00 00 00 00 00 00 00 00
// 01 (这一个字节标识枚举的成员值,1代表test1)
// 00 00 00 00 00 00 00
t = .test1(4, 5)
// 小端模式
// 06 00 00 00 00 00 00 00
// 00 00 00 00 00 00 00 00
// 00 00 00 00 00 00 00 00
// 02 (这一个字节标识枚举的成员值,2代表test2)
// 00 00 00 00 00 00 00
t = .test2(6)
// 小端模式
// 01 00 00 00 00 00 00 00
// 00 00 00 00 00 00 00 00
// 00 00 00 00 00 00 00 00
// 03 (这一个字节标识枚举的成员值,3代表test3)
// 00 00 00 00 00 00 00
t = .test3(true)
// 小端模式
// 00 00 00 00 00 00 00 00
// 00 00 00 00 00 00 00 00
// 00 00 00 00 00 00 00 00
// 04 (这一个字节标识枚举的成员值,4代表test4)
// 00 00 00 00 00 00 00
t = .test4
@platojobs platojobs added Technology technology MobileDevelopment iOS、安卓、Flutter labels Oct 21, 2021
@platojobs platojobs self-assigned this Oct 21, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
MobileDevelopment iOS、安卓、Flutter Technology technology
Projects
No open projects
PJ技术类
Awaiting triage
Development

No branches or pull requests

1 participant