Often we need to keep a property somewhere, but it needs to be a weak reference. So if the target goes out of scope, our reference should become nil. Now we can of course use WeakRef class directly for this. But that requires some work and casting on every access. It is much nicer to wrap it in a computer property. This way the compiler can check types when using the property. Internally we map back to the weakRef object. So check this code:

As you see we have a private property with the actual weakRef. The computed property getter checks if we have a WeakRef and provides value of it. We use a variant to avoid the need of explicit casting. For the setter we either set our weakRef property to nil or a new weakRef pointing to the target value.
Please use weak references always for references in data structures where a leaf references back to the tree.
15 06 14 - 12:50

one comment

Ha! I was wondering about doing that!

Does this mean there is a snowflake’s chance in hell that I might become a programmer after all?