Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of void -> (void) in Swift?

Tags:

swift

I know the meaning of (void) in objective c but I want to know what is the meaning of this code:

(Void) -> (Void) 

In Swift.

like image 257
Pooja Srivastava Avatar asked Aug 16 '16 06:08

Pooja Srivastava


People also ask

What is void in return type?

The void type, in several programming languages derived from C and Algol68, is the return type of a function that returns normally, but does not provide a result value to its caller. Usually such functions are called for their side effects, such as performing some task or writing to their output parameters.

What is void and return?

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 the function of void?

When used as a function return type, the void keyword specifies that the function doesn't return a value. When used for a function's parameter list, void specifies that the function takes no parameters. When used in the declaration of a pointer, void specifies that the pointer is "universal."


1 Answers

() -> () just means Void -> Void - a closure that accepts no parameters and has no return value.

In Swift, Void is an typealias for an empty tuple, ().

typealias Void = () The empty tuple type.

This is the default return type of functions for which no explicit return type is specified.

For an example

let what1: Void->Void = {} 

or

let what2: Int->Int = { i in return i } 

are both valid expressions with different types. So print has the type ()->() (aka Void->Void). Strictly speaking, printThat has type (() -> ()) -> () (aka (Void->Void)->Void

Void function doesn't has a lot of sense as Int function etc ... Every function in Swift has a type, consisting of the function’s parameter types and return type.

Finally, regarding "void" functions, note that there is no difference between these two function signatures:

func myFunc(myVar: String)        // implicitly returns _value_ '()' of _type_ ()
func myFunc(myVar: String) -> ()

Curiously enough, you can have an optional empty tuple type, so the function below differs from the two above:

func myFunc(myVar: String) -> ()? {
    print(myVar)
    return nil
}

var c = myFunc("Hello") /* side effect: prints 'Hello'
                       value: nil
                       type of c: ()?              */
like image 100
Amit Srivastava Avatar answered Sep 20 '22 21:09

Amit Srivastava