SE-0255: Implicit Returns from Single-Expression Functions

As I mentioned upthread, I personally don’t find this syntax to be advantageous at all. The current proposal supports “one liners” just as well as this syntax does (unless you are following a style guide that is too rigid about the formatting of single-expression bodies when they must be surrounded by braces).

If we are going to introduce a whole new syntactic form for single-expression syntactic sugar I think it should go further and also support return type inference. We support property type inference already and this would be quite similar:

let x = 2
let doubled = x * 2
func double(x: Int) = x * 2

However, this obviously does not work for computed properties, as I pointed out upthread. So I think we would need to use syntax that is different than = in order to make it work with computed properties, perhaps := (as a strawman syntax):

// This is a computed property.
// Compared to the syntax in the current proposal (below) it is shorter mostly because 
// it supports type inference, which would be even more beneficial when the type is large.
let doubled := x * 2
let doubled: Int { x * 2 }

// This is a function with an inferred result type.
// Compared to the syntax in the current proposal (below) it is shorter mostly because 
// it supports result type inference, which (as above) would be even more beneficial 
// when the type is large.
func double(x: Int) := x * 2
func double(x: Int) -> Int { x * 2 }

I’m guessing return type inference would be a non-starter. The only other benefit this syntax has is that it may feel lighter weight to some people (it does a bit to me). However, I think that is not a significant enough benefit to justify deviating from consistent use of braces.

Return type inference (and type inference for get-only computed properties and subscripts) might be enough to justify that deviation if it was on the table. However, it still feels orthogonal to this proposal. It is not in conflict with the proposed syntax which increases overall consistency in the language. The first thing I wanted to do when I learned about single-expression closure shorthand is to be able to use it in other code blocks. I’m sure I am not alone.

This rationale makes some sense from a language designer’s perspective. But from a language user’s perspective it feels inconsistent to limit it to this context. Swift will be an easier language to learn if the rule is just “you may omit return from a body that consists of a single expression” than it will be if you must append “in these specific contexts” to that rule. It’s much harder to remember a list of contexts in which the sugar is allowed than it is to just need to remember the “single expression” rule.

4 Likes