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

12,723

() -> () 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: ()?              */
Share:
12,723
Pooja Srivastava
Author by

Pooja Srivastava

I am Iphone Developer.

Updated on July 16, 2022

Comments

  • Pooja Srivastava
    Pooja Srivastava almost 2 years

    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.