Explicit control flow contradiction question

Isn't

a core principle of Swift is to make control flow explicit and visible

from this page contradicting with Implicit Returns from Single-Expression Closures and Functions With an Implicit Return?

As a side note, I personally prefer one way of doing things like this, instead of possible confusion or inconsistence. Is it just me that thinks that omitting return is confusing, for example, when quickly scanning some code? Having the return at the beginning of the line, and differently coloured by Xcode, I think makes it 100% clear that that line returns from the function, so I don't see how removing it couldn't make it less clear.

Have you come across this recent thread already?

No, I didn't find it. But I don't feel like the replies answer the question completely, as most of them were strictly related to the changes in SE-0255, whereas I was trying to start a generic conversation about optional or required return keyword, not about a specific change or case.

It does. However as with many things, it's a continuum between clarity and brevity.

If visible control flow was the only concern you should also require -> Void for all Void returning functions and, for that matter, a return Void in those same functions rather than just return. That has been deemed in many languages to be redundant and unnecessary, but its removal undoubtedly makes it less clear.

On the other hand you could allow removing return completely and always use the last expression like in kotlin. This certainly makes control flow less clear, but also enables some nice sugar that can make some usages concise while still expressive. e.g.

fun getColor(mode: ColorMode): Color = when(mode) {
    Dark -> Color.black
    Light -> Color.white

Swift's current approach allows removing redundancy where it makes sense, without losing the ability to reason about what's happening pretty quickly. Does this make it a bit harder when scanning code? Yes, though IME that's more of a learned skill that will adapt. If you still find requiring return advantageous, you can still use it. If they don't already, most linters should allow you to set a rule to require it.

1 Like

Generally speaking, the premise is that return is allowed to be omitted in single line bodies – where an actual return is always unambiguous. I do understand how this could make someone new to Swift do a double take though. And there will probably be more reasons for confusions once we support coroutines and extend the family of return-ish control flow statements. But it's also hard to imagine modern Swift without shorthand closure syntax, and the ship for that has sailed long ago.

1 Like