[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.

7 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