Swift中可以使用MemoryLayout枚举来获取某个类型所占用的内存空间,其单位为字节

3 min read

例如,获取Int类型所占用的内存空间:

let intSize = MemoryLayout<Int>.size
print(intSize) // 8(在64位平台上)

还可以使用其他枚举值来获取更详细的信息,例如对齐方式、所占用的位数等:

let intAlignment = MemoryLayout<Int>.alignment
let intStride = MemoryLayout<Int>.stride
let intBits = MemoryLayout<Int>.size * 8

print(intAlignment) // 8 (在64位平台上,对齐方式为8字节)
print(intStride) // 8 (在64位平台上,类型的内存对齐大小为8字节)
print(intBits) // 64 (在64位平台上,Int类型占用64位或8个字节)