Memory layout behaves a little strange when trying to find the size of a struct.
I can just maintain a function that adds the size of each. But I was wondering if there was a better way.
enum Mode: UInt8 {
case tings
}
// this should be 5 - UInt8 + UInt16 + UInt16
struct Stuff {
let mode: Mode
let sessionID: UInt16
let sessionCount: UInt16
}
print(MemoryLayout<Stuff>.size) // 4 ???
print(MemoryLayout<UInt16>.size) // 2
print(MemoryLayout<Mode>.size) // 0 !?!?!?!?
print(MemoryLayout<Mode.RawValue>.size) // 1
You cannot rely on simply adding together the sizes of the individual fields of a structure to get the struct's size.
Swift can add padding into the fields of a struct to align fields on various byte boundaries to improve the efficiency in accessing the data at runtime.
If you want to allocate one item, you can simply use the size
of the memory layout. If you want a contiguous block of n instances then you should allocate blocks based on the stride
of the layout.