Hello.
I’d like to propose a potential enhancement to Swift that could simplify a common pattern used in closures — the weak self (or weak variable) capture followed by a guard let check.
Currently, we often see code like this:
class DataManager {
private let service = NetworkService()
private var data: [String] = []
func fetchData() {
service.fetch { [weak self] result in
guard let self else {
return
}
data = result
}
}
}
This pattern works well to avoid retain cycles, but it can be somewhat verbose and repetitive. After seeing this pattern in many projects, I thought it might be beneficial to make it more concise and intuitive. My suggestion is to introduce a new capture type called safe, which could apply not only to self, but also to other variables that can be captured as weak or unowned:
class DataManager {
private let service = NetworkService()
private var data: [String] = []
func fetchData() {
service.fetch { [safe self] result in
data = result
}
}
}
The idea behind this is twofold:
-
Simplified syntax: No need to write
guard let self(or other variables) repeatedly. Thesafekeyword would handle this automatically. -
Compiler/runtime optimization: The
safekeyword could allow the compiler or runtime to decide whether to captureselfor other variables asweakorunowned, optimizing for both safety and performance based on the closure’s context.
This could improve readability and productivity, not just for cases involving self, but also for other variables that benefit from being captured weakly or as unowned.
You can view the proposal draft on GitHub Gist at NNNN-safe-keyword-for-closures
I’d love to hear your thoughts!
Best regards,
-Van