MemoryLayout and Alignment
Inspect size, stride, and alignment of types.
Why Memory Layout Matters
When you work with unsafe Swift or bridge to C, you need to know how values are arranged in memory. Swift gives you MemoryLayout<T> to inspect this without ever touching raw bytes.
It answers three questions: how big is a value, how far apart are values in an array, and on what address boundary must a value begin.
// MemoryLayout works on any type
print(MemoryLayout<Int>.size) // 8 on 64-bit
print(MemoryLayout<Bool>.size) // 1
print(MemoryLayout<Double>.size) // 8size — Actual Storage
MemoryLayout<T>.size is the number of bytes the value's significant data occupies. It does not include trailing padding that may sit between elements in an array.
Use size when you want to know how many meaningful bytes a single value holds.
struct Point {
var x: Int8 // 1 byte
var y: Int64 // 8 bytes
}
print(MemoryLayout<Point>.size) // 16 (not 9 — padding!)All lessons in this course
- MemoryLayout and Alignment
- UnsafePointer and UnsafeMutablePointer
- Unsafe Buffer Pointers
- withUnsafeBytes and C Interop