[swift-users] weak self

Dennis Weissmann dennis at dennisweissmann.me
Mon May 1 09:59:28 CDT 2017


> On May 1, 2017, at 4:46 PM, Rien via swift-users <swift-users at swift.org> wrote:
> 
> In my code I use a lot of queues. And (very often) I will use [weak self] to prevent doing things when ‘self’ is no longer available.
> 
> Now I am wondering: how does the compiler know that [weak self] is referenced?
> 
> I am assuming it keeps a reverse reference from self to the [weak self] in order to ‘nil’ the [weak self] when self is nilled.
> 
> But when a job is executing it has no control over the exclusive rights to [weak self].
> 
> I.e. [weak self] may be nilled by an outside event in the middle of say:
> 
> 	if self != nil { return self!.myparam }
> 
> The if finding [weak self] non nil, but the return finding [weak self] as nil
> 
> Is that correct? i.e. should we never use the above if construct but always:
> 
> 	return self?.myparam ?? 42
> 

Yes, as you said, you never know when self will be nilled out, that's why you need to create a (temporary) strong reference to it, work on it, and when the block returns, your strong reference is released and self either goes away immediately (incase it was released elsewhere after the local binding to a strong variable and no other objects had a strong reference to it) or it will stay as long as no other object holds a strong reference to it.

When the closure is more involved than a view lines, I often do a guard let `self` = self else { return } to conveniently work with a strong self inside the rest of the closure.

> Regards,
> Rien
> 
> Site: http://balancingrock.nl
> Blog: http://swiftrien.blogspot.com
> Github: http://github.com/Balancingrock
> Project: http://swiftfire.nl - A server for websites build in Swift
> 
> 
> 
> 
> 
> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

- Dennis


More information about the swift-users mailing list