Explictly capture variables in blocks

I'm a pretty big +1 on doing something in the area of this pitch (though that might just mean using a linter). But the above suggestion is the opposite of what I would like to see just based on my own experience. Using weak or unowned for one object is a huge warning sign that other objects should be explicitly captured also. [weak self] is practically a reflex, but it's very easy after that to forget about other objects.

1 Like

I think this is a good idea and should go to swift evolution. I’ve coded iOS at many levels of seniority and run teams for many years, almost all Swift in the last 5 years and almost all UI based, including a lot of RxSwift, MVVM, MVVM-C and other similar FRP styles. One of the biggest problems, especially for people coming from an existing UI skill set, is learning a reactive programming style. IMO, if code reviewers (or a linter) insisted on closures having a capture list in UI code, so many subtle bugs and memory leak would be caught early and, more importantly, code based would move to side effect free, allowing much better optimisation at some time. Plus even in very normal UI code, the idiom of adding [weak self] to closures is so universal that warnings would crop up a lot. But, as Cory said, outside of UI contexts you wouldn’t need excessive added annotations for strong capture where it’s a useful part of the language. Finally, it might enable some compiler optimisation. I’m not familiar enough with the code to know but I get the feeling it could be helpful! Personally, I like this idea!

1 Like

I think it is a valid point. I am sure a common error is capturing a reference to a value type in the closure, modify the captured value, and get surprised as if there had been a problem with respecting value semantics.