呼叫MemoryLayout<SampleStruct>.size
的奇怪结果。它在以下结构上返回41。
struct SampleStruct {
var tt: Int?
var qq: Int?
var ww: Int?
}
那不能被3整除! Int?
的平均大小为9。怎么可能?
[Int?
aka Optional<Int>
是一种enum
类型,需要9个字节:8个字节为整数(如果我们使用的是64位平台),另加1个字节作为区分大小写。
此外,通过插入填充字节,每个整数在内存中都aligned到其自然边界(8字节)。
所以您的结构在内存中看起来像这样
i1 i1 i1 i1 i1 i1 i1 i1 // 8 bytes for the first integer
c1 // 1 byte for the first case discriminator
p1 p1 p1 p1 p1 p1 p1 // 7 padding bytes
i2 i2 i2 i2 i2 i2 i2 i2 // 8 bytes for the second integer
c2 // 1 byte for the second case discriminator
p2 p2 p2 p2 p2 p2 p2 // 7 padding bytes
i3 i3 i3 i3 i3 i3 i3 i3 // 8 bytes for the third integer
c3 // 1 byte for the third case discriminator
且为41个字节。
您可以在Swift文档的Type Layout文档中找到相关的细节。