Why does the computer require a return statement?

Why does the Swift language (and can any example please be provided) permit code to exist after a return statement in a function:

fun test() -> String {

let text: String = "test1"

return text

let _: String = "test2"
}

Similarly with computed properties the compiler will struggle to infer which line to return without specifically declaring it (unless a single like of code):

let test: String {

let test1: String = "test1"
let test2: String = "test2"

return test1 + test2
}

Why not just accept that the final line of code is the one to return ?

1 Like

Several reasons. When reading a complex code block, it wouldn't always be clear if the last line is evaluated for its side effect or if it is the value to return. More fundamentally, Swift is statement-oriented not expression-oriented, so we don't think of a code block as having a value. Rather a code block is a sequence of statements evaluated in order for their side effects; a 'return' statement is a special statement which returns a value from a function.

Closures blur this distinction somewhat; the 'return' can be emitted from a single-expression closure. But fundamentally this is just simple syntax sugar, and the parser knows to insert the implicit 'return' if the body of a closure is a single expression statement.

An explicit 'return' statement also allows early returns out of a function, for example from within a nested control structure such as a loop, which is occasionally useful.

11 Likes

The compiler does produce a warning for such code (if there's really no way the code will be executed), so it should be easy enough to catch such instances. As for why it's a warning rather than an error, I often find this useful when debugging to insert an early return in some function whose behavior I want to fake—it would be higher-friction if I had to comment out and/or delete the entire remaining function body.

11 Likes