Using Structs (Bytes) with SWIFT-Struct in NSData and NSData to Struct

I am trying to understand how structures work in SWIFT. I am familiar with how .NET processes them and how it packs bytes into a structure, etc.

I find some oddities with the following code:

struct exampleStruct { var ModelNumber: Byte! var MajorVersion: Byte! var MinorVersion: Byte! var Revision: Byte! } var myStruct = exampleStruct ( ModelNumber: 1, MajorVersion: 2, MinorVersion: 3, Revision: 4 ) myStruct.MinorVersion // << Returns 3 // Struct to NSData. var data = NSData( bytes: &myStruct, length: sizeof(exampleStruct) ) println("data: \(data)") 

println returns: "data: <01000200 03000400>"

I expected that in fact the data would be like this: "data: <01020304>"

Any idea why SWIFT does not pack 1 byte into 1 byte, instead it packs bytes into 2 bytes (1 byte value and 1 byte as 00)?

On the other hand, if I do the following:

 var newStruct = exampleStruct(ModelNumber: nil, MajorVersion: nil, MinorVersion: nil, Revision: nil) var sendBytes:[Byte] = [0x1, 0x2, 0x3, 0x4] var newData = NSData(bytes: sendBytes, length: sendBytes.count) newData.getBytes( &newStruct, length: sizeof(exampleStruct) ) newStruct.MinorVersion // << Returns nil println(newData) 

println (newData) is correct and what I expect in the value: <01020304>

However, when I turn to minorVersion, it returns nil, and not what I expected as 3.

Is there a way to make the structure respect byte packing?

+6
source share
1 answer

Change Byte! on Byte .

Otherwise, you create a hold on the Optional<Byte> structure, which is more than one byte, because in addition to holding the byte, it needs an extra byte to indicate whether it is nil

Note. This may still not work, as you may need something like __attribute__((packed)) to tell the compiler how to handle alignment. AFAIK, it is not available in Swift.

+2
source

Source: https://habr.com/ru/post/979086/


All Articles