[Pitch] Last expression as return value

This is a really interesting thought! In a way, it's a similar solution to the then keyword proposal, but instead applying the "last statement is the expression value" rule only to do expressions, not more widely.

This has the big win of not requiring a keyword like then (and also eliminates the awkward parsing ambiguities).

Of course, it doesn't make everyone happy:

  • simple closures still need fiddling with just to add a second trivial statement, so it doesn't make people who are enthusiastic about this proposal happy
  • it still has an implicit last value rule for do expressions, which some folks will still find too subtle

Taking a step back for a second: speaking personally, my main goal is to lift the major limitation on if/switch expressions, and to introduce do expressions to replace the somewhat odd immediately executed closure idiom (and allowing for nice syntax for assigning results from either values or caught errors)

I feel like solving both these issues is an imperative for Swift. Inaction would be bad.

How they are solved though is where there are options. So far we have a continuum:

  • Introduce a new yielding keyword like then
  • Introduce do expressions with a last expression rule, use them to solve the if/switch limitation
  • Use trivia like ; as Rust does
  • Introduce a last expression rule for if, switch, do, but not functions/closures
  • Go all in on a last expression rule

Of all of these options, using ; is the only one I'm firmly against. I would be fairly happy with all 4 of the other outcomes. I'm currently warmest towards the full on last-expression rule, and I actually think the do option may be better than the keyword option.

edit: realized I was missing a middle ground option

16 Likes