[swift-evolution] A compiler option to warn if a closure captures a strong reference to a class instance?

Anton Mironov antonvmironov at gmail.com
Mon Feb 20 11:40:38 CST 2017

Hi. I’ve come to this issue too.
I thought that current Swift memory model is good enough to solve this in the other way. I've put self (aka ExecutionContext) as an argument to map/filter/etc. This looked like I'm binding execution to the specified context. It might sound odd, but it actually fits nicely into some kind of actor model. It opened such possibilities as automatic cancellation of async execution if there is no context that will use results of the execution.
Ended up developing a library that incorporates this idea AsyncNinja <https://github.com/AsyncNinja/AsyncNinja> sometimes looks even better then RxSwift <https://github.com/AsyncNinja/AsyncNinja#comparison-with-rxswift>. I also wrote an article <https://medium.com/@AntonMironov/moving-to-nice-asynchronous-swift-code-7b0cb2eadde1#.mfw3lbxiq> that shows advantages of the approach.
Please tell me if it makes sense for you.

Anton Mironov

> On Feb 20, 2017, at 1:22 PM, Lauri Lehmijoki via swift-evolution <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). 
> 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?
> B) Should we add a compiler option that, when turned on, would emit a warning if a closure strongly captures a class instance?
> Regards
> Lauri
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170220/adf47ba1/attachment.html>

More information about the swift-evolution mailing list