Weak vs Unowned in iOS Swift

This article explains the basic difference between weak and unowned in iOS Swift. You will also learn when and where to use these two in code.

iOS Essentials


Before explaining about weak and unowned, we should know what ARC (Automatic Reference Counting) is and how memory is managed in iOS.

ARC is an automatic memory management mechanism through which the OS frees up memory based on reference counts. This means that it only frees up memory for objects when there are zero strong references to them.

Reference: Apple Docs

The memory management model is based on object ownership. Any object may have one or more owners. Retain Count or retain count represents the number of owners for a particular object. As long as an object has at least one owner, it continues to exist. If an object has no owners, the runtime system destroys it automatically.

Note: ARC is only applicable for reference types. For ex: Class, functions, closures etc. Not applicable for value times like struct and enum.

Apple docs: Reference counting applies only to instances of classes. Structures and enumerations are value types, not reference types…