In C, the order in which you define fields in a struct is the order in which they will be instantiated in memory. Taking into account memory alignment, the following struct will have a size of 8 bytes in memory as shown, but only 6 bytes if the fields are reversed as there doesn't need to be any alignment padding.
struct s {
int32_t a;
/* 2 bytes of padding to align a 64 bit integer */
int64_t b;
}
This ordering guarantee is present in C structs, C++ classes (and structs), and Objective-C classes.
Is the order of storage similarly guaranteed for fields in Swift classes and structs? Or (given that the language doesn't support pointers in the same way as the others listed), does the compiler optimally re-arrange them for you at compile-time?
It seems that the order is guaranteed.
Given the following struct:
Alignment is still happening. There's a lost 8 bits there between
c
andb
.Of course, it's not clear whether these bits are actually between
c
&b
or just tacked at the end... until we rearrange:I believe this behavior matches the other languages you mentioned in your question.
Yes, the order of the struct elements in memory is the order of their declaration. The details can be found in Type Layout (emphasis added). Note however the use of "currently", so this may change in a future version of Swift:
The padding/alignment is different from C:
Only if a struct is imported from C then it is guaranteed to have the same memory layout. Joe Groff from Apple writes at [swift-users] Mapping C semantics to Swift
and later in that discussion:
Example:
Here
var d: UInt8
is layed out in the tail padding ofvar sa: A
. If you define the same structures in Cand import it to Swift then
because
uint8_t d
is layed out after the tail padding ofstruct CA sa
.As of Swift 3, both
size
andstride
return the same value (including the struct padding) for structures imported from C, i.e. the same value assizeof
in C would return.Here is a simple function which helps to demonstrate the above (Swift 3):
The structures defined in Swift:
The structures imported from C: