UnsafePointer and UnsafeMutablePointer
Read and write raw memory carefully.
Typed Pointers in Swift
Swift's safe references never expose raw addresses, but when interoperating with C or building low-level data structures you reach for typed pointers: UnsafePointer<T> for read-only access and UnsafeMutablePointer<T> for read/write.
A typed pointer knows the element type, so it can compute strides and read a properly-typed value.
// A pointer to an Int we can read but not write
func readFirst(_ p: UnsafePointer<Int>) -> Int {
return p.pointee
}The pointee Property
pointee is the value the pointer currently addresses. On a mutable pointer you can both read and assign it; on a read-only pointer you can only read.
Accessing pointee on uninitialized or deallocated memory is undefined behavior — the type system will not catch it.
let p = UnsafeMutablePointer<Int>.allocate(capacity: 1)
p.initialize(to: 42)
print(p.pointee) // 42
p.pointee = 99
print(p.pointee) // 99All lessons in this course
- MemoryLayout and Alignment
- UnsafePointer and UnsafeMutablePointer
- Unsafe Buffer Pointers
- withUnsafeBytes and C Interop