Can someone explain me the following behaviour in Swift?
func test() -> Bool {
print("1 before return")
return false
print("1 after return")
}
func test2() {
print("2 before return")
return
print("2 after return")
}
test()
test2()
returns:
1 before return
2 before return
2 after return
I would expect that print("2 after return")
would never be executed since it is after a return
statement.
Is there something I am missing?
(tested with Swift 4 / 4.1 & Xcode 9.2 / Xcode 9.3 beta 2)
It is a tricky thing, Swift doesn't require semi-colons (they are optionally used), this makes Swift compiler automatically deduce whether is the next line should be a new line, or a completion for the old one.
print()
is a function that returns void. So the wordreturn print("something")
, is valid. Socould be deduced as
return print("Something")
Your solution is to write
func test2()
is similar tofunc test2() -> Void
So your code gets treated as,
Adding semicolon after print should fix it.
You can also see the error if you place value type after return line and you will understand more,
When I tried this in the IBM Swift Sandbox I got the following warning:
which pretty much explains the issue. Swift is interpreting it as if you had written:
The print statement is executed and the return value of the print
()
is returned.Adding
;
after the return makes that a separate statementand then the warning becomes:
Answer extracted from question:
It seems the problem is, that swift does not exit the function instantly on a return statement in a void function and uses the consecutive
void
value as the function parameter and terminates as expected if it is non-void.If Xcode would work reliably this message should be shown on the next examples:
is the same as
and since print(...) has the same signature it is ok to call return print(...) in a void function