[Pitch] Proposal for `safe` keyword in closures to simplify `weak` capture pattern

It was someone else who brought up "control flow" in the conversation I quoted. I'm focusing on the "expressive power" part.

Consider:

func banana(f: (Int) -> Int?) { ... }

// A:
banana() { [weak self] n in
    guard let self else { return nil }
    return n * myvar
}

// B:
banana() { [guard self] in $0 * myvar }

I would say allowing a one-liner B to truly be that without the boilerplate of A is more of an win for expressiveness than, say, being able to omit the second half of if let a = a.

Sure, but the rationale in the original decision you quoted is specifically calling out the level of improvement in expressiveness necessary to justify introducing new sources of control flow. It’s totally consistent with that rationale to accept smaller improvements in expressiveness when not introducing such sources.

8 Likes

-1 for the mentioned reasons (explicitness, flexibility, etc). Consider the use cases of logging before returning, or returning some value, or doing an extra logic before returning, or throwing instead of returning, or calling a never returning function instead of returning, or etc.

If that's what you want:

            guard let self else {
                return
            }

just put it on the single line:

            guard let self else { return }
2 Likes

Hello Folks,

Thank you all for your contributions and thoughts on this pitch. It’s been fascinating to see the range of responses—some people seemed to misunderstand the purpose, others understood but didn’t find it necessary, while some agreed with the idea. However, it seems this isn’t a priority for the Core Team, given their silence, nor for other active members of the community.

For now, I’ll leave this as a potential topic to revisit in the future. In the meantime, it looks like we’ll all continue writing the same repetitive guard let self else { return } code to achieve exactly what this pitch proposed—but without the luxury of direct language support. After all, why simplify if we can complicate things just a bit more, right? (Just kidding! …Or am I?)

Jokes aside, I truly hope Swift continues to evolve in 2025—becoming simpler, not more complex—and that it keeps empowering developers everywhere. Wishing everyone a great end to 2024 and an excellent 2025! :tada:

-Van