NEW: Master Swift design patterns with my latest book! >>

How weak references work in Swift 4

Paul Hudson    September 23rd 2017    @twostraws

Mike Ash's latest Friday Q&A takes a walk through weak references in Swift 4, comparing the old implementation against the new. From the article:

In the old implementation, Swift objects have two reference counts: a strong count and a weak count. When the strong count reaches zero while the weak count is still non-zero, the object is destroyed but its memory is not deallocated. This leaves a sort of zombie object sitting in memory, which the remaining weak references point to. When a weak reference is loaded, the runtime checks to see if the object is a zombie. If it is, it zeroes out the weak reference and decrements the weak reference count. Once the weak count reaches zero, the object's memory is deallocated. This means that zombie objects are eventually cleared out once all weak references to them are accessed.

In the old implementation, it's possible zombie objects could hang around long after they were needed, which could be a real waste of memory. Fortunately, times have moved on and Swift's new implementation manages to solve that problem using side tables. Mike explains:

Swift's new implementation of weak references brings with it the concept of side tables. A side table is a separate chunk of memory which stores extra information about an object. It's optional, meaning that an object may have a side table, or it may not. Objects which need the functionality of a side table can incur the extra cost, and objects which don't need it don't pay for it.

One thing I really enjoy about Mike's blog posts is that he is careful to link to the matching source code in Swift, so you can see for yourself exactly how things are implemented. Yes, I know all the Swift source code is there to read, but it can be so hard to find an entry point without someone to give you a pointer – make sure you read the whole article!

Link: Friday Q&A 2017-09-22: Swift 4 Weak References

 

About the author

Paul Hudson is the creator of Hacking with Swift, the most comprehensive series of Swift books in the world. He's also the editor of Swift Developer News, the maintainer of the Swift Knowledge Base, and Mario Kart world champion. OK, so that last part isn't true. If you're curious you can learn more here.

Click here to visit the Hacking with Swift store >>