Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

early return from a void-func in Swift?

Tags:

swift

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)

like image 872
d.felber Avatar asked Feb 20 '18 14:02

d.felber


People also ask

Can you return something from a void function?

Void functions do not have a return type, but they can do return values.

What is a void function in Swift?

-> 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 ().

Does return exit the function Swift?

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.

What would be the return type of a function if the return type is not defined Swift?

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.


1 Answers

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")
like image 198
user9335240 Avatar answered Sep 18 '22 19:09

user9335240