Friday, August 1, 2014

Swift Retain/Release and Pointer Arithmetic

Russ Bishop (via Wolf Rentzsch):

While creating ThreadLocalSlot<T>, I needed to call the posix posix_getspecific and posix_setspecific methods. Not only that, I needed to store an Objective-C object in a plain old void*. How can we accomplish that in Swift?

The key is Unmanaged. It contains magic sauce to let us turn an AnyObject into a COpaquePointer, which is implicitly convertible to most of the other C-pointer types in Swift. It also lets us apply retain or release to an object arbitrarily. Granted, you can certainly shoot yourself in the foot, but we all lived dangerously before ARC.

Russ Bishop:

You might end up kicking yourself, but UnsafePointer<T> and its cousins all have arithmetic operators already defined so pointer manipulation is very simple:

Comments RSS · Twitter

Leave a Comment