Today, let's look at Swift's implicit pointer support which can simplify our code quite a bit and works great when the callee doesn't keep the pointer alive or when it understands Objective-C and can handle retain/release/autorelease semantics. For some of the readers this will be extremely simple stuff, but I want to cover it for completeness.
A really simple case is a C function that takes an
int * parameter:
If you try this example, you'll notice an error "Int is not identical to Int32". If you have control of the function or method, you can use
NSInteger or the more portable
intptr_t. Swift will automatically handle either one as
int32_t on 32-bit systems and
int64_t on 64-bit systems which matches the behavior of Swift's
Int type. Alternatively, you can declare
var x:Int32 to match the required size.
As long as
smashIt doesn't stash the pointer somewhere and attempt to use it later (possibly after the object containing
var x has been deallocated) it should be smooth sailing.
Simple object pointers like
SomeClass* are recognized by Swift and handled automatically, but when dealing with the case of
SomeClass**, we can take advantage of Swift's ability to implicitly construct an
AutoreleasingUnsafePointer<T?> and ARC (we can always use
Unmanaged<T> when we need to do manual memory management).
Here Swift will allocate storage and pass the address of that storage to the method; when returning, it will assume the object is autoreleased and ready to participate in normal ARC memory management. The equivalent to NULL is also simple and straightforward: just pass
If you're storing a pointer to an Objective-C object in a location that is not aware of ARC (like a
void *), see the previous parts of this series for examples. You must do an unbalanced retain of the object to keep it alive, otherwise you'll end up with a dangling pointer and much sadness.
Next time: Let's dynamically create some structs
Part 1 Swift: Manual retain/release
Part 2 Swift: withUnsafePointerToElements
Part 3 Swift: Pointers everywhere
Part 4 Swift: Interop in Beta 3
This blog represents my own personal opinion and is not endorsed by my employer.