4

I'm trying to rewrite an iOS app from objective c into swift. I'm using serialization in order to send data over some sort of communication layer. In objective c I used #pragma pack (1) at the top of each struct in order to use sequential layout without padding between the data members. I tried to use PRAGMA_STRUCT_PACK at the top of the struct. It seems to work at the playground, but when implementing it in my app, I got an error message saying: "Expressions are not allowed at the top level".

from playground enter image description here

Slava Kamzen
  • 519
  • 4
  • 18

2 Answers2

1

Swift doesn't support explicitly specifying the data layout of structure types. (At least, not currently. File a bug if there are features you'd like to see and maybe Apple will put them in a future version?) For now your best bet is probably to declare layout-sensitive structures (and functions to access them) in C and call those from Swift.

Writing PRAGMA_STRUCT_PACK in Swift source gives you an error because that macro, once imported from C, evaluates to the literal 1. In C, you're supposed to use that macro to detect whether the compiler supports #pragma pack (before going on to issue a #pragma pack directive).

(You're probably seeing confusing answers/comments because lots of people were looking for #pragma mark during the early Swift betas. But this isn't the #pragma they're talking about.)

Community
  • 1
  • 1
rickster
  • 124,678
  • 26
  • 272
  • 326
  • `PRAGMA_STRUCT_PACK` actually works perfectly fine in Swift (because Swift imports it from the C headers). The problem is not that Swift has no preprocessor, but that `PRAGMA_STRUCT_PACK` is actually just defined as the value `0` or `1` based on whether the C compiler supports `#pragma pack` (and in this case it evaluates to `1`). – Lily Ballard May 06 '15 at 16:53
-7

Swift is not C. If you care about layout of structures in memory, you are in the wrong place. I mean why on earth would you be interested in that kind of implementation detail? Swift will layout things the way it wants and no other way. It's not an assembly language.

BTW. Trying to use packed structures for serialization is totally misguided. Create an array of bytes and write to it what you want to write.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • 3
    "I mean why on earth would you be interested in that kind of implementation detail?" - because sometimes you get a block of memory that actually contains data of a pakced struct, e.g. when you receive an IP packet on a raw network socket or when parsing a binary file type with fixed size headers. If there was no use case for controlling packing, why do you think compilers/languages do even offer that feature? – Mecki Jul 06 '16 at 09:02