Swift: Pointer Arithmetic
Abandon all hope of safety
Update: I originally did not make it clear but if Swift knows the type of the unsafe pointer then arithmetic will operate on sizeof(T)
not on bytes! The same goes for alloc
. So my example below with an UnsafePointer<Float32>
will jump forward 25 * sizeof(Float32)
bytes.
I've seen a lot of people wondering how to do raw pointer arithmetic, usually involving a C struct for some data complex data structure they can't or don't want to convert to Swift.
You might end up kicking yourself, but UnsafePointer<T>
and its cousins all have arithmetic operators already defined so pointer manipulation is very simple:
let ptr:UnsafePointer<()> = ...
let newPtr = ptr + 10 //move forward 10 bytes
If you want to cast pointers, use the trick I showed you in my post about querying DNS:
let floatValue = UnsafePointer<float32>(ptr + 25) //offset 25
Obviously if the bytes starting at offset 25 from ptr
do not represent a float32
then the results are undefined. You should treat use of UnsafePointer<T>
, especially uses that involve pointer arithmetic or casting, as dangerous and require strict code review.
So to the brave and foolhardy, have at it!
This blog represents my own personal opinion and is not endorsed by my employer.