MemoryLayout and Alignment
Inspect size, stride, and alignment of types.
MemoryLayout and Alignment is a free Swift Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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!)stride — Spacing in Arrays
stride is the distance in bytes between the start of one element and the next when values are packed in a contiguous array. It equals size rounded up to the alignment.
When you allocate buffers manually, you multiply by stride, never by size.
print(MemoryLayout<Point>.stride) // 16
print(MemoryLayout<Int8>.stride) // 1
// Buffer for 10 Points needs:
let bytes = 10 * MemoryLayout<Point>.stride // 160alignment — Address Boundaries
alignment is the byte boundary on which a value must start. An Int64 with alignment 8 must begin at an address divisible by 8. The compiler inserts padding to honor this.
A struct's alignment is the largest alignment of its members.
print(MemoryLayout<Int8>.alignment) // 1
print(MemoryLayout<Int64>.alignment) // 8
print(MemoryLayout<Point>.alignment) // 8The size vs stride Difference
For many types size == stride, but they diverge whenever padding exists. A struct may have size 9 yet stride 16 because the next element must be 8-byte aligned.
Rule of thumb: reason about a single value with size, reason about collections with stride.
struct Mixed {
var flag: Bool // 1
var value: Int // 8
}
print(MemoryLayout<Mixed>.size) // 16
print(MemoryLayout<Mixed>.stride) // 16Field Offsets
For structs you can ask where each stored property sits relative to the start using MemoryLayout<T>.offset(of:) with a key path. This is essential when laying out data to match a C struct.
struct Header {
var magic: UInt32 // offset 0
var length: UInt64 // offset 8 (padded)
}
print(MemoryLayout<Header>.offset(of: \Header.magic) ?? -1) // 0
print(MemoryLayout<Header>.offset(of: \Header.length) ?? -1) // 8Reordering to Save Space
Because of alignment, the order of stored properties affects size. Putting larger fields first or grouping by size can shrink a struct. This matters for large arrays where wasted bytes add up.
struct Wasteful { var a: Int8; var b: Int64; var c: Int8 } // size 24
struct Tight { var b: Int64; var a: Int8; var c: Int8 } // size 16
print(MemoryLayout<Wasteful>.size)
print(MemoryLayout<Tight>.size)Layout of References
A class instance is heap-allocated, so a variable holding a class reference is just a pointer. Its MemoryLayout.size is the pointer size (8 bytes), regardless of how big the object is.
Value types like structs store their contents inline; reference types store only the pointer.
class Big { var data = [Int](repeating: 0, count: 1000) }
print(MemoryLayout<Big>.size) // 8 — just the referenceOptionals and Enums
Optionals usually add a byte for the tag, but Swift optimizes reference optionals to reuse the null pointer, so String? can be the same size as String.
Enums with associated values are sized to hold their largest case plus a discriminator.
print(MemoryLayout<Int?>.size) // 9
print(MemoryLayout<String>.size) // 16
print(MemoryLayout<String?>.size) // 16 — no extra byteUsing of: with an Instance
Every member (size, stride, alignment) also has an instance-based form: MemoryLayout.size(ofValue:). This is handy when the type is hard to spell out or inferred.
let tuple = (UInt8(1), UInt64(2))
print(MemoryLayout.size(ofValue: tuple)) // 16
print(MemoryLayout.stride(ofValue: tuple)) // 16
print(MemoryLayout.alignment(ofValue: tuple)) // 8Allocating With Correct Layout
When you allocate raw memory you must pass both byte count and alignment. Getting these from MemoryLayout guarantees correctness across architectures rather than hardcoding numbers.
let count = 4
let capacity = count * MemoryLayout<Int>.stride
let align = MemoryLayout<Int>.alignment
let raw = UnsafeMutableRawPointer.allocate(
byteCount: capacity, alignment: align)
defer { raw.deallocate() }Quick Check
Test your understanding of size versus stride.
Recap
You learned the three pillars of memory layout:
- size — meaningful bytes of a single value
- stride — spacing between array elements (use this for allocation)
- alignment — required start boundary
You also saw offset(of:) for field positions, how property order affects size, and that references are just pointer-sized. These tools let you allocate and interpret raw memory safely.
Frequently asked questions
Is the “MemoryLayout and Alignment” lesson free?
Yes — the full text of “MemoryLayout and Alignment” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.
What will I learn in “MemoryLayout and Alignment”?
Inspect size, stride, and alignment of types. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Swift Academy?
No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “MemoryLayout and Alignment” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Swift Academy lesson?
Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- MemoryLayout and Alignment
- UnsafePointer and UnsafeMutablePointer
- Unsafe Buffer Pointers
- withUnsafeBytes and C Interop