Pitch: Weak method storage modifiers (aka weak references)

Interesting. It seems to me like this approach might lead to confusion about the behavior of capture specifiers because it allows a library to effectively turn every capture into a weak capture. For example, somebody might write a type that exposes an addObserver(_ observer: @escaping (Event) -> Void) method and stores the closures with weak references with the idea that users won't need to specify weak self.

If this style of API became common people may begin to think less about how they capture objects. It also introduces the need for libraries to document how they store closures and for users to be aware of the semantics the library uses. It would probably lead to requests to introduce a reallyStrong capture specifier (name intentionally awkward) that is strong even in the presence of a weak reference to the closure.

I gave some thought to this problem space last year and was heading in the direction of introducing guarded closures. I was working on a second draft incorporating some of the feedback from that thread when I decided to set it aside. This design makes capture semantics clear at the declaration site of the closure but supports an "inverted" default that is sugar for closures that (mostly) capture weak with a guard on the weak captures at the beginning of the closure. It also allows an API to "invert" the default by using @guarded instead of @escaping, requiring users to provide a guarded closure. Users would still be able to use explicit strong captures where necessary.

I recently started a new thread for guarded closures when the topic came up in The Future Of [weak self] Rebinding. It's clear that there is a lot of interest in doing something in this area. It's less clear what the right balance is. :slight_smile:

1 Like