Pooja Srivastava
Pooja Srivastava

Reputation: 721

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

I know the meaning of (void) in Objective-C but I want to know what is the meaning of this code in Swift:

(Void) -> (Void)

Upvotes: 10

Views: 18255

Answers (3)

Sofeda
Sofeda

Reputation: 1371

Same meaning in Swift. No parameter no return value.

Upvotes: -1

Sagar Ajudiya
Sagar Ajudiya

Reputation: 53

Void is a data type that is common across a lot of programming languages, in Swift’s standard library, it’s simply an empty tuple. It’s used for for functions that return nothing.

When defining a function, if you don’t specify a return type, you get a function that return Void; this is how it’s defined in the standard library:

public typealias Void = ()

You use Void to declare the type of a function, method, or closure...

Keep in mind that () can mean two things:

  • () can be a type – the empty tuple type, which is the same as Void.
  • () can be a value – an empty tuple, which is the same as Void().

Upvotes: 1

Amit Srivastava
Amit Srivastava

Reputation: 1105

() -> () 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: ()?              */

Upvotes: 28

Related Questions