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)
Void functions do not have a return type, but they can do return values.
-> Void is just an explicit way of saying that the function returns no value. From docs: Functions without a defined return type return a special value of type Void. This is simply an empty tuple, in effect a tuple with zero elements, which can be written as ().
After a return statement, Swift will execute a function that returns Void before exiting that function. In the above example, since the print function returns Void it will be executed before exiting myFunction.
Any function that does not return a value has a special return type named Void . When we do not specify a function return type, we have simply told swift that the return type is a void hence our function must not return anything.
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 word return print("something")
, is valid. So
return
print("Something")
could be deduced as return print("Something")
Your solution is to write
return;
print("Something")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With