Honestly, I think this is one of the rougher parts of the language to see 
problems in. In my opinion, anything that can be done to either warn of retain 
cycles or enforce a better practice in this would be valuable.
Josh

On Mar 3, 2017, at 1:14 PM, Alex Johnson via swift-evolution 
<swift-evolution@swift.org<mailto:swift-evolution@swift.org>> wrote:

Hi list members,

During code review today, I noticed a really subtle memory leak that looked 
like:

    self.relatedObject = RelatedObject(callback: relatedObjectDidFinish)

Where `relatedObject` is a strong reference, `callback` is an escaping closure, 
and `relatedObjectDidFinish` is a method of `self`. From a memory management 
perspective, this code is equivalent to:

    self.relatedObject = RelatedObject(callback: { self.relatedObjectDidFinish 
})

In the second example, an explicit `self.` is required. It’s my understanding 
that this is to highlight that the closure keeps a strong reference to `self`. 
But, when passing a method, there is no such requirement, which makes it easier 
to accidentally create a retain cycle.

This made me wonder if an explicit `self.` should be required when passing a 
method as an escaping closure. And whether that would help in the same way that 
the explicit `self.` *inside* the closure is intended to.

If it were required, the code in the first example would be:

    self.relatedObject = RelatedObject(callback: self.relatedObjectDidFinish)

What do you think?

Alex Johnson
ajohn...@walmartlabs.com<mailto:ajohn...@walmartlabs.com>
ajohnson on Slack
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org<mailto:swift-evolution@swift.org>
https://lists.swift.org/mailman/listinfo/swift-evolution



Joshua Parmenter | Engineering Lead, Apple Technologies

T 248 777 7777
C 206 437 1551
F 248 616 1980
www.vectorform.com<http://www.vectorform.com/>

Vectorform
2107 Elliott Ave Suite 303
Seattle, WA  98121 USA

Think Tank. Lab. Studio.
We invent digital products and experiences.

SEATTLE | DETROIT | NEW YORK | MUNICH | HYDERABAD

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to