Reputation: 2598
I tested some code to understand completion handlers, and I found that there are types such as ()->()
and ()
.
I know ()->()
means "no parameters and no return value"; but what type is ()
?
If I define a function like this:
func sayHello(){
print("hello")
}
and then check the type:
type(of: sayHello) // ()->()
type(of: sayHello()) // ()
Is "function execution" (()
), a type?
Upvotes: 1
Views: 67
Reputation: 17572
typealias Void = ()
The return type of functions that don't explicitly specify a return type; an empty tuple (i.e., ()).
When declaring a function or method, you don't need to specify a return type if no value will be returned. However, the type of a function, method, or closure always includes a return type, which is Void if otherwise unspecified.
Use Void or an empty tuple as the return type when declaring a closure, function, or method that doesn't return a value.
Upvotes: 0
Reputation: 318924
What you are really asking is why does type(of: sayHello())
result in ()
.
Start by thinking about what sayHello()
does. It actually calls the function. So type(of:)
is telling you the type of the result of that call. Since the return type of sayHello
is Void
, the type is ()
. It's basically the second ()
of () -> ()
seen in the first call to type(of:)
.
If you change sayHello
to have a return type of Int
instead of Void
, then the 2nd type(of:)
returns Int
instead of ()
. And the 1st type(of:)
would change from () -> ()
to () -> Int
.
tl;dr - ()
represents Void
. The return type of calling sayHello()
.
Upvotes: 3