I think that's the key point.
Regardless of one's personal preferences, it is definitely true that for very short code branches (one-liners is best, but also 2-3 lines is fine) the return
keyword doesn't appear particularly necessary at end of the branch, because the fact that a value is being returned from the expression is clear from the immediate code context. The canonical example of adding a print
in a case:
branch of a switch
shows this really well.
But it's just not true that return
is also not useful for long code branches, with several statements: the return
there is useful, serves a purpose, it's just not true that it's "useless" and "noise". One can get "used to it", but it's always still going to be useful, as it would also be useful to have different keyword to express the returned value from a multiline expression, in order to be able write proper structured code, with early exits, as we do in every other case in Swift.
I mean, today we can write this perfectly fine code, that uses excellent control flow techniques that are clear to understand and are compiler-aided:
func foo() {
let xs = [1, 2, 3, 4]
for x in xs {
doSomething(with: x)
guard x > 2 else { continue }
print(x)
doSomethingElse(with: x)
}
}
// will print 3 and 4
Without a new keyword to bind the returned value from an expression, for example a do
expression, I wouldn't be able to use guard
in there, and this is inconsistent. It's not "inconsistent" to be able to omit return from a one-liner compared to a 100 lines function, because those are completely different cases, and there is a very good reason to omit return
from a one liner (or even a 2-3 liner), while there is no good reason to omit it from a 100 lines function.
The argument that a new keyword would make the language more complex looks like a misunderstanding of the word "complexity": the complexity comes from the use cases themselves, it's essential, and the language is just there to express that complexity in code, and it can do it in good ways and bad ways. Specifically, I think that:
- a new keyword will be clear, explicit and will allow for proper control flow in multiline expressions;
- considering the last expression as return value will be useful in a limited number of cases, but will not allow for expressing full control flow in multiline expression, and will make longer and more complex multiline expressions (and functions in general) harder to understand.