Tuesday, November 24, 2015

How Swift Implements Unowned and Weak References

Joe Groff:

Unowned is faster and allows for immutability and nonoptionality. If you don’t need weak, don’t use it.

unowned uses a second refcount in the object. weak refs are tracked in a global table.

It’s a space/time tradeoff. unowned can’t free memory until unowned refs die, but weak frees immediately when strong refs die.

Yeah, so we can check whether the object is still alive before strong-retaining it again.

The object is destroyed and gives up all its resources when the last strong reference is released.

The memory for the instance is still allocated but left in a zombie state.

This is so that Swift can guarantee that if you try to access it you get an error rather than a crash or the wrong data. If you don’t want that overhead:

There’s unowned(unsafe), which is completely unmanaged.

With weak references, the memory can be freed immediately. This is safe because the references are zeroed, but it’s more cumbersome because you have to deal with optionals.

2 Comments RSS · Twitter


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


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

Leave a Comment