Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift function with Void return type versus no return type

I'm struggling with understanding return values in Swift. Can you explain the difference between these?

func someFunc() -> Void {}
func someFunc() {}
like image 663
Alexey Savchenko Avatar asked Sep 06 '16 04:09

Alexey Savchenko


People also ask

Should I put return in a void function?

A void function cannot return any values. But we can use the return statement. It indicates that the function is terminated. It increases the readability of code.

What is never return type when to use it over void in Swift?

The Never return type is a special one in Swift, and tells the compiler that execution will never return when this function is called. It's used by Swift's fatalError() and preconditionFailure() functions, both of which cause your app to crash if they are called.

What is the difference between return function and void function?

Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value.

When a method has a return type of void What does that mean?

A void return type simply means nothing is returned. System. out. println does not return anything as it simply prints out the string passed to it as a parameter.


1 Answers

Simply, there is no difference. -> 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 ().

Thus, these three function declarations below are same:

func someFunc() {}
func someFunc() -> Void {}
func someFunc() -> () {}
like image 128
Ozgur Vatansever Avatar answered Oct 18 '22 15:10

Ozgur Vatansever