ARC In Swift


arc, swift

ARC In Swift


Daniel Shin - May 05, 2015

Swift uses Automatic Reference Counting(ARC) like Objective-C to perform garbage collection.

Automatic Reference Counting is basically Swift keeping track of the number of pointers that reference a certain memory address, and when that number of references count down to zero, program automatically garbage collect the memory in that memory address, whether it be a tiny scalar value or couple of gigabytes video source.

Automatically managed memory means one less mundane housekeeping required for programmers. But this comes with caveat.

That is, there is a chance for memory leak caused by Strong Reference Cycle.

When you declare a variable that references a certain object that is stored in memory, it ‘strongly’ references that object in memory. This usually isn’t not a problem since when variables that reference a certain memory all go out of scope, that memory will be freed naturally.

Problem arises when these variables somehow reference each other. This creates a strong reference cycle. And since neither of them will ever drop reference counting to zero (since they reference each other), neither of their referenced memory will ever be freed.

Swift provides an elegant solution to this by offering weak, unowned references.

weak reference doesn’t create strong reference cycle. By specifying one of the two strong references to weak, you declare that this pointer should not be counted in Automatic Reference Counting. By breaking one of the two strong references, it successfully break strong reference cycle.

unowned is similar to weak reference type in that it doesn’t get counted for ARC, but it differs by its nature of being non-optional. weak reference is optional whereas unowned is always non-optional. Think it as the difference between optional and forced unwrapped optional.

unowned reference that points to nil will result in runtime error so you should only use unowned when you are certain that the memory object will always be present when the variable is being access even though this variable doesn’t explicitly holds onto that memory address since it strongly references it. Instead that memory object must be strongly referenced by another variable, and that variable must be present at all time throughout the lifecycle of this unowned variable.

weak variable being forced unwrapped is semantically equivalent to unowned variable.