Swift calculates the wrong size of the structure

Today I had a problem with Swift structures. See the following structure, for example:

struct TestStruct { var test: UInt16 var test2: UInt32 } 

I would suggest that the size of this structure is 6 bytes in total, because UInt16 is 2 bytes and UInt32 is 4 bytes.

The following code prints 6 (this is correct):

 println(sizeof(UInt32) + sizeof(UInt16)) 

But if I check the size of the structure with

 println(sizeof(TestStruct)) 

he prints 8, not 6.

If I try to do the same with the following structure:

 struct TestStruct2 { var test: UInt16 var test2: UInt16 var test3: UInt16 } 

Then

 println(sizeof(TestStruct2)) 

displays the correct value: 6. But the size of TestStruct should be the same as the size of TestStruct2.

Why is the first structure 8 bytes in size? Am I doing something wrong or is this a mistake?

(tested with Xcode 6.1.1 (6A2008a) on OS X Mavericks, the usual command line application for Mac)

+7
struct sizeof xcode swift
source share
1 answer

This is because Swift aligns the UInt32 field at the 4-byte boundary, inserting a two-byte "gap" between UInt16 and UInt32 . If you switch the fields so that there is a 32-bit field first, the gap would be eliminated:

 struct TestStruct1 { var test: UInt16 var test2: UInt32 } println(sizeof(TestStruct1)) // <<== Prints 8 struct TestStruct2 { var test2: UInt32 var test: UInt16 } println(sizeof(TestStruct2)) // <<== Prints 6 

You can also put another UInt16 in this space without resizing your structure:

 struct TestStruct3 { var test0: UInt16 var test1: UInt16 var test2: UInt32 } println(sizeof(TestStruct3)) // <<== Prints 8 

But then, how can I get data from NSData into this aligned structure? If I use data.getBytes(&aStruct, length: sizeof(AStruct)) , then I have the wrong values.

Optional: if you saved AStruct using the same method, then spaces will also be present in NSData , so getting your binary data will be like placing a cookie cutter on a pre-filled byte array with the same alignment.

+8
source share

All Articles