[swift-users] weak self
glessard at tffenterprises.com
Tue May 2 09:59:25 CDT 2017
> On May 2, 2017, at 00:05, Rien <Rien at balancingrock.nl> wrote:
> Interesting: this is a kind-of symmetry break between optionals and weak references.
> I.e. most (inexperienced?) programmers will see a strong similarity between weak references and optionals.
> And for a lot of use cases they do indeed behave similar.
> But for weak references I think the guideline should be: Never ‘force-unwrap’ it.
> Maybe this should be mentioned in the swift guide?
> Maybe even include a warning in the compiler for this?
I also don’t think there’s a symmetry break there. A weak reference is effectively a shared variable between threads, so its value can change between any two actions. This would be the same if it were an Optional that happens to be shared between threads, but you’d have to handle locking yourself. An `if let` binding to a strong reference is effectively a lightweight lock against deletion of your object.
The more critical thing is that if you need to perform more than one action with a weak reference, you really should bind it to a strong reference first. The optional chaining approach is a fine shortcut for a single action.
More information about the swift-users