Swift Alignment

In Swift 4, the structure MemoryLayouttells you the tags size, strideand alignment.

I understand size and step, but not alignment really.

Is there an example that shows what alignment is, how it differs from a step, when it has a different meaning from a step, and where it would be wrong to use a step, but use alignment correctly?

Is it possible to always calculate one from the other?

+4
source share
1 answer

Here is a simple example:

struct Foo {
    let a: Int16
    let b: Int8
}

print(MemoryLayout<Foo>.size)       // 3
print(MemoryLayout<Foo>.alignment)  // 2
print(MemoryLayout<Foo>.stride)     // 4
  • Alignment of the structure is the maximum alignment of all its fields, in this case, the maximum 2and 1.
  • The step of the structure is the size rounded to alignment, here it is 3rounded to a multiple 4.

- () :

let array = [Foo(a: 1, b:2), Foo(a: 3, b: 4), Foo(a: 5, b: 6)]
array.withUnsafeBytes {
    print(Data($0) as NSData) // <01000234 03000474 0500066f>
    print($0.count) // 12
}

, (, , ) .

:

, . :

  • 0 1.
  • , var . :
    • , , , .
    • .
    • Update , .
    • .
  • . .
+8

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


All Articles