Pitch: Syntactic sugar for circumventing closure capture lists

If you take a look at github repos and just to try find:

guard let strongSelf = self else { return }
guard let `self` = self else { return }`
...

you will get bazillion results.
The main problem is to understand when weak unowned should be used and even for experienced Swift users it is sometimes hard to grasp which one should be used as it strongly depends on the context. Thats why we have such situations were people add [weak self] regardless if is needed or not but it’s easier, and faster to add this than thinking about each case and for sure finding a memory leak which in case of closures is rarely pleasant experience.

I believe that whole community would love to see improvement in this area as writing guard let for self became like a mantra. We can improve this situation by compiler warnings and better tooling or/and improving the syntax of closures to lesser the problem.

I would be personally satisfied if at least for closures that returns Void we could solve it by the syntax sugar in a form that was already proposed few times. For any other closure I don’t think we need any additional syntax as probably it won’t be significantly shorter and more descriptive than typing guard inside the closure as we use to now.

{ [weak(guard) self] in ... }
{ [unowned(guard) self] in ... }

I would only suggest to even use shorter syntax to avoid writing weak and unowned and instead ? and !

{ [guard self?] in ... }
{ [guard self!] in ... }
2 Likes