Call a closure with a pointer to the given argument.
The withUnsafePointer(to:_:) function calls a closure with an UnsafePointer to the given value. The pointer is only valid for the duration of the closure and must not be stored or returned.
This is useful for interoperating with C APIs that expect pointer arguments, or for inspecting the memory layout of a value.
For mutable access, use withUnsafeMutablePointer(to:_:) instead. Always ensure pointer usage stays within the closure's scope to avoid undefined behavior.
| Name | Description | Optional |
|---|---|---|
value |
The value to pass as a pointer. | No |
body |
A closure that receives an UnsafePointer to the value. | No |
var x = 42
withUnsafePointer(to: &x) { ptr in
print(ptr.pointee) // 42
}