Difference between weak and unowned in swift.

Shantaram Kokate
2 min readMar 15, 2019

--

To avoid the retain cycle we have to specify the relationship between two object i.e weak, unowned, strong

A varible reference to an instance is strong by default. But that is not always what you want. If a strong reference is not appropriate, you have a few alternative options, weak and unowned references.

A weak or unowned instance reference count neaver increase.

Weak

Let us visualize.

  1. Weak always declared as an optional.it may contain nil or actual type.
  2. The value of a weak reference needs to be unwrapped before it can be accessed.

When to use :

When you not sure that an instance will always exist for the lifetime.

For example:

  • weak owner will not sure that an instance will always exist. Because at any time it will contain an actual value or nil.
  • To avoid code crash make sure that captured instance never to nil using guard statement.

Unowned

Let us visualize.

  1. Unowned always has an actual type.
  2. you can directly access the value of an unowned reference.
  3. an unowned reference is deallocated, it isn’t set to nil. As a result, a fatal error is thrown if the referenced object of the unowned reference is ac accessed.

When to use :

When you sure that an instance will always exist for the lifetime.

How to use :

For example:

  • the unowned owner sure that an instance will always exist for the lifetime in clouser.
  • Our code will crash if the owner instance is deallocated. So be careful while using the unowned.

In next article we will see the Swift Memory Management — Autorelease pool

https://medium.com/@shantakokateit/swift-memory-management-autorelease-pool-eea16d3863eb

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Shantaram Kokate
Shantaram Kokate

No responses yet

Write a response