Advanced Swift: Memory Management · Unowned | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/1940727-advanced-swift-memory-management/lessons/3

Why so complicated solution .
It could have been explained better .
There was no mention of how does using weak and unowned reduces or does not increase the reference count .

Hi Ray

Can you please explain in what scenarios should one use weak while in which cases would ‘unowned’ work better?

I like to make a parallel optional types which you might have more familiarity with.

When you say something is unowned you are asserting that the object will outlive the thing accessing it. In the same way, if I have let person: Person! I am asserting that person.name will always work because person is non nil (and if that is not true, the program will trap at runtime).

When I say something is weak I am saying that the object can come and go (and it automatically switches to nil when all the reverse go away. As long as I access the weak optional types checking the value it will never trap at runtime.