0Pricing
Swift Academy · Lesson

withUnsafeBytes and C Interop

Bridge to C APIs that expect raw bytes.

From Typed to Raw Bytes

Sometimes you need to see a value not as an Int or a struct, but as a sequence of raw bytes — to hash it, write it to a file, or hand it to a C API. withUnsafeBytes gives you exactly that: a temporary view of a value's storage as UInt8.

var value: UInt32 = 0x01020304
withUnsafeBytes(of: &value) { rawBuffer in
    print(rawBuffer.count) // 4 bytes
}

The UnsafeRawBufferPointer

The closure receives an UnsafeRawBufferPointer — a buffer of bytes with no element type. You index it to read individual UInt8 values. It is read-only; the mutable form is withUnsafeMutableBytes.

var value: UInt32 = 0x01020304
withUnsafeBytes(of: &value) { bytes in
    for b in bytes { print(String(format: "%02x", b)) }
}
// Order depends on endianness

All lessons in this course

  1. MemoryLayout and Alignment
  2. UnsafePointer and UnsafeMutablePointer
  3. Unsafe Buffer Pointers
  4. withUnsafeBytes and C Interop
← Back to Swift Academy