Friday, July 24, 2015

Weak and Unowned References in Swift

Hector Matos:

At this point we have a retain cycle. You see, closures in Swift behave exactly like blocks in Objective-C. If any variable is declared outside of the closure’s scope, referencing that variable inside the closure’s scope creates another strong reference to that object. The only exceptions to this are variables that use value semantics such as Ints, Strings, Arrays, and Dictionaries in Swift.

Here, NSNotificationCenter retains a closure that captures self strongly when you call eatHuman(). Best practice says that you clear out notification observers in the deinit function. The problem here is that we don’t clear out the block until deinit, but deinit won’t ever be called by ARC because the closure has a strong reference to the Kraken instance!

Other gotchas where this could happen is in places like NSTimers and NSThread.

The fix is to use a weak reference to self in the closure’s capture list. This breaks the strong reference cycle.


Weak and unowned references are essentially the same. It does not increase the retain count of the object being referred. However, in Swift, an unowned reference has the added benefit of not being an Optional.

5 Comments RSS · Twitter

Unowned pointers are a slightly safer "unsafe unretained" pointer.

in what way Chris?

They don't increase the retain count of the object, but they also don't automatically drop to nil, this means that they can dangle. This makes them more efficient and somewhat more convenient than weak pointers, but also less safe. They do have some additional runtime checks that unsafe unretained pointers in objc arc don't though.

[…] Weak and Unowned References in Swift, How Swift Implements Unowned and Weak […]

[…] Weak and Unowned References in Swift, How Swift Implements Unowned and Weak References, Swift’s Lazy Weak […]

Leave a Comment