Weak references

Weak references don’t play any part in the reference count of a certain object. You declare them as optionals, so they become nil once the reference count reaches zero.

An editor doesn’t always have a tutorial assigned, so it makes perfect sense to model the editor’s tutorial property as a weak reference because it will be nil at some point in the future. Change the property’s declaration in the Editor class to the following:

weak var tutorial: Tutorial?

You break the reference cycle with the weak keyword; both deinitializers run and print the following output to the console now:

Goodbye Memory management! Goodbye Ray!

Note: You can’t define a weak reference as a constant because it will be set to

nil at some point during runtime.

There’s one more way to break reference cycles between class instances: unowned references.

results matching ""

    No results matching ""