iosswiftautomatic-ref-countingunowned-references

Why can't I give an unowned constant an initial value?


class Example {}
unowned let first = Example()

This produces the error:

Attempted to read an unowned reference but object 0x60c000005f20 was already deallocated

I'm trying to dig deep into understanding exactly what keyword unowned does.


Solution

  • From The Swift Programming Language:

    Like a weak reference, an unowned reference does not keep a strong hold on the instance it refers to.

    You create a new instance of Example, and assign it to your unowned constant first. There is nothing holding a strong reference to your Example instance so it is immediately deallocated. Your unowned constant first is now holding a reference to this deallocated object so you get the error that you are attempting to read a deallocated object.

    The unowned keyword is used to create a weak reference to an object where you can guarantee that the lifetime of the referenced object is the same as the referring object. This enables you to prevent reference loops while avoiding the need to unwrap an optional (as would be the case with weak).