[swift-evolution] A compiler option to warn if a closure captures a strong reference to a class instance?
milseman at apple.com
Mon Feb 20 15:57:03 CST 2017
> On Feb 20, 2017, at 9:09 AM, David Hart via swift-evolution <swift-evolution at swift.org> wrote:
>> On 20 Feb 2017, at 12:22, Lauri Lehmijoki via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>> I'm developing an application where we use RxSwift heavily. RxSwift is a stream library. Consequently, closures that we pass to its combinators often live infinitely (this is because one can use RxSwift to represent infinitely long sequences in time).
> I used RxSwift extensively and that’s not what I have experienced. I have streams with lifetimes dependent on the lifetime of the DisposeBag they are added to, which is itself linked to the lifetime of the current View Controller or View Model. And that very closely resembles the way closures work in the Cocoa APIs (UIAlertAction handlers, etc…). I don’t think RxSwift is at odds.
>> Closures with infinite lifespan have implications for the question "what is the best reference capture mode for closures". My experience is that in RxSwift applications, the current default (strong) is almost always suboptimal. It leads to difficult-to-detect memory leaks and introduces a "gotcha" factor to programmers who are new to Swift. I'd prefer the default to be weak capture.
>> So, I'd like to ask you two things:
>> A) By default, why the Swift closure captures values strongly?
> If the default were weak, it would litter closures with ?
> If the default were unowned, your programs would crash without you understanding.
> I think its a sensible default.
>> B) Should we add a compiler option that, when turned on, would emit a warning if a closure strongly captures a class instance?
> Perhaps we can improve the situation, but I’m not sure that is the solution. Sometimes I want my references to be strongly captured and I don’t want a warning to pollute by build output.
In general, these should not be warnings as Swift tries to avoid effective language dialects through warnings. But, this would be an awesome lint rule!
>> swift-evolution mailing list
>> swift-evolution at swift.org <mailto:swift-evolution at swift.org>
> swift-evolution mailing list
> swift-evolution at swift.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the swift-evolution