I'm struggling with understanding return values in Swift. Can you explain the difference between these?
func someFunc() -> Void {}
func someFunc() {}
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.
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.
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.
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.
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() -> () {}
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