[Pitch] Last expression as return value

Multiple people (including me) in this thread have raised the question of how this proposal interacts with Result Builders. If I'm not mistaken, I don't believe these questions have been fully addressed within this thread, however, it looks like they have already been addressed in SE-0380:

The expression is not part of a result builder expression

if and switch statements are already expressions when used in the context of a result builder, via the buildEither function. This proposal does not change this feature.

The variable declaration form of an if will be allowed in result builders.

If I understand this correctly, it's saying that already, today, if an if or switch is used in the context of a Result Builder, then the Result Builder will take precedence, so the buildEither function will be used, and the in-place if/switch expression will not be used. (That is as long as the user doesn't explicitly opt-in to if expression syntax by writing something like:

let foo = if a { "A" } else { "B" }

So it seems whatever ambiguity there could be with Result Builders, is leftover ambiguity that already exists today (since Result Builders can be implicitly applied already, like on body in the View protocol). This proposal doesn't seem to increase ambiguity (at least when it comes to code that a human could interpret as either an if expression or a buildEither).

@localhost shared this example:

var body: some View {
    Text("Foo")
    Text("Bar")
}

which is currently interpreted as something like:

var body: some View {
    Group {
        Text("Foo")
        Text("Bar")
    }
}
// `body` evaluates to something like TupleView<Text, Text>

Presumably, after this proposal, it would be interpreted as this:

var body: some View {
    Text("Foo") // ⚠️ Unused expression.
    return Text("Bar") // this return is implicit
}
// `body` evaluates to just Text

The warning would immediately draw attention to the cause of the problem, but this would be a breaking change in many code bases.

It seems worth considering if the "last expression as return value" rule should not apply within Result Builders (just like if/switch expressions already don't apply within Result Builders).

(This behavior may already be intended, but I don't think I saw it mentioned explicitly in the proposal.)

4 Likes