Swift Retain/Release and Pointer Arithmetic
Russ Bishop (via Wolf Rentzsch):
While creating ThreadLocalSlot<T>, I needed to call the posix
posix_getspecific
andposix_setspecific
methods. Not only that, I needed to store an Objective-C object in a plain oldvoid*
. How can we accomplish that in Swift?The key is
Unmanaged
. It contains magic sauce to let us turn anAnyObject
into aCOpaquePointer
, which is implicitly convertible to most of the other C-pointer types in Swift. It also lets us applyretain
orrelease
to an object arbitrarily. Granted, you can certainly shoot yourself in the foot, but we all lived dangerously before ARC.
You might end up kicking yourself, but
UnsafePointer<T>
and its cousins all have arithmetic operators already defined so pointer manipulation is very simple: