programming, swift

Swift 3.0 Unsafe World

Like most of the modern languages, in Swift you will be living in a happy world where all the memory is managed by an external element, it could be the compiler/runtime like swift or it could be worse and depend on a garbage collector. References to instances that fly around are hidden in the language and rarely you need to deal with these issues.

However, given Swift versatility you could need to call a dirty C Api like OpenGL or POSIX functions, and in those cases you will need to deal with that thing that has caused lots of headaches to many of us, yes, I'm talking about pointers and allocating memory manually in the heap

Before 3.0, Swift unsafe API was a little bit confusing, there were several paths to achieve the same result, and that caused that you usually ended by copying and pasting what you saw in stackoverflow without understanding what is really happening. In 3.0 everything has changed, and it has done it for the better.

In this post I won't write how to migrate from Swift 2.x to 3.0 code, instead I will describe how the things works in 3.0 and will be comparing occasionally with C, since usually the main purpose of using unsafe references is to interact with low level C APIs.

Let's start by doing the simplest operation, allocating memory to hold an Integer.

Continue reading