Press "Enter" to skip to content

Pointers in Swift 3

Let’s reverse a null-terminated string in Swift. First, the code.

This example is a bit contrived, if you wanted to reverse a string in Swift it would be much easier to use the String(reverse.characters.reversed()) method.

First thing, when working with pointers in Swift, is to allocated memory for them. Here I’m using ptrCapacity to allocate space for the array of CChar that will represent the string we are going to reverse. ptrCapacity in this case will be the same size of reverse.characters.count, however I wanted to have a reminder there of MemoryLayout. MemoryLayout helps describe the memory layout of a given type and can be useful if you’re working with pointers. The process of calling allocate is similar in C/C++ to calling malloc(sizeof(CChar)).

So now that the pointer is allocated we initialize it with our null-terminated string. In Swift 3 utf8CString replaces nulTerminatedUTF8. advance advances the pointee (formally memory) by some count. It is defined as self + count. There are a few ways to get at the data in our array. Any of the following would work.

subscript : ptr[index]
advance : ptr.advance(by: index).pointee
arithmetic : (ptr + index).pointee

The main difference being subscript returns the pointee, whereas the others return an UnsafeMutablePointer

The algorithm runs it’s course, the string is reversed, and the last thing we need to do is deinitialize the memory our pointer is using and deallocate it. If you’re coming from C/C++ this would be the same as calling free.

The intent of this post was for me to attempt to use pointers in Swift. If you need to work with C libraries there are a number of pointer classes in the standard library that are incredibly useful.

There was one thing that I found a bit odd, when checking for null pointers when the pointer and/or pointee are non-optional. For instance,

I couldn’t find a good way to check to see if a non-optional pointer is null or not. It would be nice to have some way to check the print before it dies.

Swift is all about safety, and playing with pointers can be a bit unsafe, so why do it? Well one reason would be if you had to work with null-terminated strings. Null reference exceptions happen, so try and be careful, but remember to have fun playing with pointers in Swift. For me this was just another experiment, hoping to learn a bit more each time I play.

Links to check out:
UnsafeMutablePointer Reference
Usafe Swift: For Fun & Profit
Using Swift with Cocoa and Objective-C
Optional Unsafe Pointers

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *